限制 mousemove 事件每秒触发不超过 5 次

Ken*_* .J 4 javascript jquery

我有一个绑定到 mousemove 处理程序的事件处理程序,它将通过 console.log() 记录当前鼠标位置。我的目标是每秒触发事件不超过 5 次,以防止在我移动鼠标时被淹没.

目前,我有下面的代码,它在每次移动时记录鼠标位置,没有限制它,我似乎无法弄清楚出了什么问题

//Code runs after document is ready

function logMouse(event){
    console.log('The mouse is currently at ('+event.pageX+','+event.pageY+')');
  }
  $(document).on('mousemove',function(event){
    setTimeout(function(){
      logMouse(event);
    },200);
  });  
Run Code Online (Sandbox Code Playgroud)

我试图通过使用 setTimeout 来限制 mousemove 事件,并将计时器设置为 200 毫秒,以便它会在 1 秒内触发 5 次,但我的代码不起作用,目前只是给我大量的鼠标位置,每当我移动我的鼠标。

我如何限制我的 mousemove 以使其每秒记录鼠标位置不超过 5 次?

Pur*_*ari 6

添加一个变量来跟踪事件刚刚发生的时间,并setTimeout在允许下一个事件之前休眠。

var timesPerSecond = 5; // how many times to fire the event per second
var wait = false;
$(document).on('mousemove', function (event) {
    // don't handle events when one has just occurred
    if (!wait) {
        // fire the event
        logMouse(event);
        // stop any further events
        wait = true;
        // after a fraction of a second, allow events again
        setTimeout(function () {
            wait = false;
        }, 1000 / timesPerSecond);
    } 
});
Run Code Online (Sandbox Code Playgroud)