Debouncing

If you listen to mousemove, scroll or window resize, they'll fire 100's of times very quickly. So its a good practise to 'debounce' them.

Normal way


function somefunc(){
    // business logic
}

window.addEventListener('resize', function(){
    somefunc();
});
            

Debounced resize event

This debounced resize event will only fire if there is no subsequent window resizing event for 150ms.


function _resize(a, b) {
    return window.addEventListener("resize", function() {
        clearTimeout(b),
            b = setTimeout(a, 150)
    }), a
}
            

usage


function somefunc(){
    // business logic
}

_resize(function() {
    somefunc();
})(); // the ending (); will run the function on load as well

            

Debounced resize event (width only)


function _resize(a, b) {
    var c = [window.innerWidth];
    return window.addEventListener("resize", function() {
        var e = c.length;
        c.push(window.innerWidth);
        if (c[e] !== c[e - 1]) {
            clearTimeout(b);
            b = setTimeout(a, 150);
        }
    }), a
}
            

This is almost the same as the above, with the only exception being that it debounces on width resize events only, so if the height chages (with no change in width) then nothing will happen.

This can be particularly useful since when you scroll up-and-down a page on mobile, the menu/url bar will show/hide - which changes the height of the browser window, and so fires a resize event.

Debounced mousemove


function _mousemove(a, b) {
    return window.addEventListener("mousemove", function() {
        clearTimeout(b);
        b = setTimeout(a, 200);
    }), a;
}
            

Debounced scroll


function _scroll(a, b) {
    return window.addEventListener("scroll", function() {
        clearTimeout(b);
        b = setTimeout(a, 200);
    }), a;
}
            

A debounced mousemove event will only fire if the mouse moves, and is then stationary for 200ms. Use it the same way as the debounced resize event.

A debounced scroll event will only fire when the user scrolls the page, and then stops for 200ms. Use it the same way as the debounced resize event.

Demo

Normal

resize events fired:    0
mousemove events fired: 0
scroll events fired:    0

Debounced

resize events fired:    0
resize width only:    0
mousemove events fired: 0
scroll events fired:    0