Javascript setTimeout not working | onkeydown

Javascript setTimeout not working | onkeydown

本文关键字:onkeydown working not setTimeout Javascript      更新时间:2023-09-26

我想做的是,当您按住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>

使用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 = '';
}

tri this

$(document).ready(function(){
   $(document).on('keydown',function(e){
      // content
   });
});
<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>

这与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上演示。