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?
The frequency rate of events while the pointing device is moved is implementation-, device-, and platform-specific, but multiple consecutive mousemove events SHOULD be fired for sustained pointer-device movement, rather than a single event for each instance of mouse movement.
Throttling is a technique in which, no matter how many times the user fires the event, the attached function will be executed only once in a given time interval. For instance, when a user clicks on a button, a helloWorld function is executed which prints Hello, world on the console.
Debounce vs. Throttle. The major difference between debouncing and throttling is that debounce calls a function when a user hasn't carried out an event in a specific amount of time, while throttle calls a function at intervals of a specified amount of time while the user is carrying out an event.
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With