【问题标题】:Throttling a mousemove event to fire no more than 5 times a second限制 mousemove 事件每秒触发不超过 5 次
【发布时间】:2020-09-16 21:59:47
【问题描述】:

我有一个绑定到 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);
  });  

我正在尝试通过使用 setTimeout 来限制 mousemove 事件,并将计时器设置为 200 mse,以便它会在 1 秒内触发 5 次,但我的代码无法正常工作,目前只是给了我一大堆鼠标每当我移动鼠标时的位置。

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

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    添加一个变量来跟踪事件刚刚发生的时间,并在允许下一个事件之前使用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);
        } 
    });
    

    【讨论】:

      【解决方案2】:

      我在整个项目中都使用这个包装函数。不幸的是,在撰写本文时,我不知道正确的术语throttling

      // ignore fast events, good for capturing double click
      // @param (callback): function to be run when done
      // @param (delay): integer in milliseconds
      // @param (id): string value of a unique event id
      // @doc (event.timeStamp): http://api.jquery.com/event.timeStamp/
      // @bug (event.currentTime): https://bugzilla.mozilla.org/show_bug.cgi?id=238041
      ignoredEvent: (function () {
          var last = {},
              diff, time;
      
          return function (callback, delay, id) {
              time = (new Date).getTime();
              id = id || 'ignored event';
              diff = last[id] ? time - last[id] : time;
      
              if (diff > delay) {
                  last[id] = time;
                  callback();
              }
          };
      })(),
      

      你可以这样使用它:

      $(document).on('mousemove',function(event){
          ignoredEvent(function(){
              logMouse(event);
          }, 200, 'mouse-move');
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多