Javascript setTimeout 不工作 | onkeydown

Javascript setTimeout not working | onkeydown

我想做的是,当您按住 ws 时,它应该每秒调用一次函数。但现在它只会延迟第一次调用,然后每秒调用 12 次。提前感谢任何愿意回答的人。我想知道更多信息就问。

<!DOCTYPE html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function call(direction) {
    $.ajax({ url: '/' + direction });
}
</script>
<script>
document.onkeydown = function (event) {
    var key_press = String.fromCharCode(event.keyCode);
    var key_code = event.keyCode;
    if (key_press == "W") {
        direction = 'down';
    } else if (key_press == "S") {
        direction = 'up';
    }
    var update = setTimeout(function () {
        call(direction)
    }, 250);

}
document.onkeyup = function (event) {
    clearTimeout(update);
}
</script>
<script type="text/javascript">
    function call(direction) {
        $.ajax({ url: '/' + direction });
    }

    var update, direction, key = null;

    document.onkeydown = function (event) {
        var key_press = String.fromCharCode(event.keyCode);
        var key_code = event.keyCode;
        if (key_press == "W" && key != "W") {
            key = "W";
            direction = 'down';
            update = setInterval(function () { call(direction); }, 1000);
        } else if (key_press == "S" && key != "S") {
            direction = 'up';
            key = "S";
            update = setInterval(function () { call(direction); }, 1000);
        }

    }
    document.onkeyup = function (event) {
        clearInterval(update);
    }
</script>

三这个

$(document).ready(function(){
   $(document).on('keydown',function(e){
      // content
   });
});

使用 setInterval 而不是 setTimeout。也考虑将更新作为全局变量。

var update = '';
document.onkeydown = function (event) {
    var key_press = String.fromCharCode(event.keyCode);
    var key_code = event.keyCode;
    if (key_press == "W") {
        direction = 'down';
    } else if (key_press == "S") {
        direction = 'up';
    }
  if (!update) {
      update = setInterval(function () {
      call(direction)
     }, 1000);
   }     

}
document.onkeyup = function (event) {
    clearInterval(update);
    update = '';
}

这与 debounce 函数的工作方式很相似,这是我尝试解决您的问题的方法:

function debounce(callback, ms){
    var timeOutId;
    window.addEventListener('keydown', function(evt){
        var key = String.fromCharCode(evt.keyCode);
        if(['W','S'].indexOf(key) !== -1 && !timeOutId){
            timeOutId = setTimeout(function(){
                callback(evt);
                timeOutId = null;
            }, ms);
        }
    });
    window.addEventListener('keyup', function(evt){
        clearTimeout(timeOutId);        
    });
}

debounce(function(){ /* your function */}, 1000); 

演示 JSFiddle