限制为每秒两个键盘输入

Restrict to two keyboard inputs per second

本文关键字:两个 键盘 输入      更新时间:2023-09-26

我正在尝试用HTML5 Canvas制作一个简单的游戏。我想要的是,每秒最多两个键盘输入。

这是我迄今为止的代码:

function move( x, y, r ) {
  var canid=document.getElementById("draw");
  canid.addEventListener('keydown',readkey,false);
  function readkey(e) {
    if(e.keyCode == 37) {
      clearField();
      x = x-draw.width / 10;
      redrawpic(x,y,r);
    }
    else if(e.keyCode == 38){
      clearField();
      y = y-draw.height / 10;
      redrawpic( x, y, r );
    }
    //..........etc
  }
}

移动功能用于将图片从一个单元格移动到另一个单元格。如何在两次移动之间设置延迟a?

您可以使用时间戳来检查上次事件发生的时间:

function move(x,y,r){
   /* your variable declarations*/
   var d1 = Date.now();
   var d2;
        function readkey(e){
             d2 = Date.now();
             // difference between timestamps needs to be 500ms
             if(d2-d1 > 500){
                  // set old Timestamp to new one
                  d1 = d2;
                  /*
                     Rest of your code
                  */
             }

这允许每500毫秒发生一次关键事件。与1秒内发生2个事件不同(可能在50毫秒内发生,然后暂停950毫秒),但可能足够近?

超时/间隔也是可能的,但我个人不喜欢连续(可能是不必要的)超时调用的开销。

var throttle = false;
function readkey(e) {
    if (throttle)
        return;
    throttle = true;
    setTimeout(function () { throttle = false; }, 500);
    /* the rest of your code */

500ms是每秒两个输入,但它们是单独节流的。你也可以统计一秒钟内有多少输入。类似的东西

    if (throttle > 1)
        return;
    throttle++;
    setTimeout(function () { throttle = 0; }, 1000);