How do you lower the frequency of Javascript event polling? The events I'm concerned about are onResize
and onScroll
. These events may be triggered dozens of times per second when someone resizes their browser or scrolls down, respectively. I'd like these events to happen only once every 500 ms so I don't have to spend hours optimizing my event handlers and making sure they don't leak memory.
var resizeTimeout;
window.onresize = function() {
if (resizeTimeout) {
clearTimeout(resizeTimeout);
}
resizeTimeout = setTimeout(function() {
// Do it!
}, 500);
});
This will trigger the setTimeout()
function ~500ms after the person has finished resizing.
The onscroll
version is very similar :)
You can't really control how frequently the event fires, you can do something like remember the time of first event firing, then on each consequent one you check if it's more than 500 ms from first one - if yes, you proceed with the event handler, otherwise you just exit the event hanlder
At the beginning of your handler, check to see if 500ms have passed since the last one, and just return if not.
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