Search code examples
javascriptevent-handlingdom-eventsonscrollonresize

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.


Solution

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