限制mousemove事件每秒触发不超过5次 [英] Throttling a mousemove event to fire no more than 5 times a second
问题描述
我有一个绑定到mousemove处理程序的事件处理程序,它将通过console.log()记录当前鼠标的位置.我的目标是使该事件每秒触发不超过5次,以防止每次我被淹没移动鼠标.
I have an event handler bound to the mousemove handler which will log the current mouse position via console.log().I am aiming to have the event fire no more than 5 times a second so as to prevent being overwhelmed whenever i move my mouse.
当前,我有下面的代码,每次移动时都会记录鼠标的位置,但是没有限制它,而且我似乎无法弄清楚出了什么问题
Currently, i have the code below, which is logging the mouse position everytime it moves, BUT is not throttling it and i can't seem to figure out what's going wrong
//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毫秒,以便在1秒内触发5次,但是我的代码无法正常工作,目前只给了我大量的鼠标每当我移动鼠标时就可以保持位置.
I am trying to throttle the mousemove events by using setTimeout, and setting the timer to 200 mse so that it would fire 5 times in 1 second, but my code isn't working and is currently just giving me a mass of mouse positions whenever i move my mouse.
如何控制鼠标移动,使其每秒记录鼠标位置不超过5次?
How do i throttle my mousemove so that it performs the logging of the mouse's position no more than 5 times a second?
推荐答案
我会用一个变量来做到这一点.
I would do it this way, with a variable.
var wait = false;
$(document).on('mousemove',function(event){
if(!wait){
logMouse(event);
wait = true;
setTimeout(function(){ wait = false; },200);
}
});
这篇关于限制mousemove事件每秒触发不超过5次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!