Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  167] [ 5]  / answers: 1 / hits: 10656  / 10 Years ago, sun, april 20, 2014, 12:00:00

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);
});


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.



How do i throttle my mousemove so that it performs the logging of the mouse's position no more than 5 times a second?


More From » jquery

 Answers
0

Add a variable that tracks when an event has just occurred, and sleep with setTimeout before allowing the next event.


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);
}
});

Alternatively, you can avoid the setTimeout and just track the latest time when an event has occurred.


var timesPerSecond = 5; // how many times to fire the event per second
var waitUntil = 0;
$(document).on('mousemove', function (event) {
// don't handle events when one has just occurred
if (Date.now() >= waitUntil) {
// fire the event
logMouse(event);
// stop any further events for a moment
waitUntil = Date.now() + 1000 / timesPerSecond;
}
});

[#45882] Friday, April 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
everardo

Total Points: 406
Total Questions: 104
Total Answers: 92

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;