我的keydown事件是运行太多次,如果我点击按钮

My keydown event is runs too many times if i click the button

本文关键字:如果 按钮 事件 keydown 运行 太多 我的      更新时间:2023-09-26
$(document).keydown(function(e) {
      if(e.keyCode == 37) { // left
            e.preventDefault();
            $("#news_container_inner").animate({
                // zuun
                left: (int_px($("#news_container_inner").css("left")) + 945) > 0 ? MAX_LENGTH : "+=945"
            });
            $('#dragBar').animate({
                left: (int_px($("#dragBar").css("left")) - dragBar_road) < 0 ? MAX_LENGTH_Drag+1 : "-="+dragBar_road
            });
            console.log('left');
      }
      else if(e.keyCode == 39) { // right
        e.preventDefault();
        $("#news_container_inner").animate({
          // baruun
          left: (int_px($("#news_container_inner").css("left")) - 945) < MAX_LENGTH ? 0 : "-=945"
        });
        $('#dragBar').animate({
            left: (int_px($("#dragBar").css("left")) + dragBar_road) > MAX_LENGTH_Drag+1 ? 1 : "+="+dragBar_road
        });
        console.log('right');
      }
    });
这是我的代码。问题是,如果我点击右箭头按钮1秒这个事件运行35次。我需要绑定它3或4次,如果我点击1秒。抱歉我的英语不好。

如果你只想触发它,你可以使用计数器,例如4次:

var counter = 0;
$(document).on('keydown', function(e) {
    e.preventDefault();
    counter++;
    if(counter > 4) {
        return;
    }
    if(e.keyCode == 37) { 
        console.log('left');
    } else if(e.keyCode == 39) {      
        console.log('right');
    }
}).on('keyup', function(e) {
    counter = 0;
});

演示

编辑

如果你想限制每秒的事件数,你可以使用setInterval:

var counter = 0,
    intervalInited = false;
function initInterval() { 
    intervalInited = true;
    setInterval(function(){
        if(counter > 4) {
            counter = 0;
        }
    }, 1000);
}
$(document).on('keydown', function(e) {
    e.preventDefault();
    counter++;
    if(counter > 4) {
        if(!intervalInited) {
            initInterval();
        }
        return;
    }
    if(e.keyCode == 37) { 
        console.log('left');
    } else if(e.keyCode == 39) {      
        console.log('right');
    }
}).on('keyup', function(e) {
    counter = 0;
});
演示