I'm reading the events chapter in Eloquent Javascript, and I have encountered the following code. Which is supposed to display the coordinates of the user's mouse every 250ms.
function displayCoords(event) {
document.body.textContent =
"Mouse at " + event.pageX + ", " + event.pageY;
}
var scheduled = false, lastEvent;
addEventListener("mousemove", function(event) {
lastEvent = event;
if (!scheduled) {
scheduled = true;
setTimeout(function() {
scheduled = false;
displayCoords(lastEvent);
}, 250);
}
});
I'm not understanding how the scheduling is working though. I understand that if you set a timeOut the handler will run after the set period of time, but I don't understand why in this example there exists a scheduled variable and a conditional statement to check its boolean value.
Without the variable and the if statement the program doesn't work as intended, it will print the coordinates without any kind of delay. What is the logic behind this?
scheduled flag purpose is to prevent the creation of a timer on each mousemove event call. Only after the current setTimeout is done, and the flag is false, a new setTimeout will be created.
Without the flag, the first call to displayCoords would come after 250ms, but subsquent calls to displayCoords will be fired one after the other, as each mousemove produced a timer, without waiting for the previous one to end.
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