Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lower the frequency of Javascript event polling

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.

like image 641
JoJo Avatar asked Dec 07 '10 02:12

JoJo


3 Answers

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 :)

like image 137
alex Avatar answered Nov 09 '22 04:11

alex


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

like image 5
Andrey Avatar answered Nov 09 '22 04:11

Andrey


At the beginning of your handler, check to see if 500ms have passed since the last one, and just return if not.

like image 1
Lou Franco Avatar answered Nov 09 '22 05:11

Lou Franco