jQuery:较少触发mousemove事件 [英] jQuery: Fire mousemove events less often

查看:97
本文介绍了jQuery:较少触发mousemove事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一种干净的方法来聚集mousemove事件,以确保代码被调用,但每250-300毫秒才调用一次.

I'm trying to figure out a clean way to aggregate mousemove events so that I ensure my code gets called, but only once every 250-300 milliseconds.

我已经考虑过使用类似以下内容的方法,但想知道是否存在更好的模式,或者jQuery提供的功能可以完成以下操作:

I've thought about using something like the following, but was wondering if there was a better pattern, or something jQuery provides that will do the same thing:

var mousemove_timeout = null;

$('body').mousemove(function() {
  if (mousemove_timeout == null) {
    mousemove_timeout = window.setTimeout(myFunction, 250);
  }
});

function myFunction() {
  /*
   * Run my code...
   */

  mousemove_timeout = null;
}

编辑:下面接受的答案在这种情况下将非常适用,但是,我发现答案中提供的mousestop()功能实际上消除了我对聚合的需求,因此,如果您阅读此问题并寻找答案,看看 mousestop 插件是不是真的需要!

The accepted answer below would work perfectly for this situation, however, I found that the mousestop() functionality provided in the answer actually eliminated my need for the aggregation, so if you're reading this question and looking for an answer, see if the mousestop plugin is what you really need!

推荐答案

您的代码很好,除了您应该清除超时,然后将其设置为null,否则可能会泄漏:

Your code is fine except that you should clear the timeout before setting it to null or it might leak:

window.clearTimeout(mousemove_timeout);
mousemove_timeout = null;

作为替代方案,您可以在以下位置使用mousemove/ mousestop window.setInterval

As an alternative you could use mousemove/mousestop in conjunction with window.setInterval

var timer = null;
var isIntervalSet = false;

$('body').mousemove(function() {
    if (isIntervalSet) {
        return;
    }
    timer = window.setInterval(function() {
        /*
        * Run my code...
        */    
    }, 250);
    isIntervalSet = true;
}).mousestop(function() {
    isIntervalSet = false;
    window.clearTimeout(timer);
    timer = null;
});

这篇关于jQuery:较少触发mousemove事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆