Search code examples
javascriptlodashthrottling

lodash.throttle - throttled method not being called?


I have an event listener, for which I am trying wrap with lodash.throttle:

import throttle from "lodash.throttle"

const throttledHandleResize = () => { 

    return(throttle(() => {
        console.log("resizing...");
    }, 200));
};

window.addEventListener("resize", throttledHandleResize);

The console does not log my string. The method works if I do not try to wrap it with throttle.

Any assistance would be much appreciated!


Solution

  • You're creating a function that returns the throttled function. Every time resize occurs, you're creating a new throttled function. Just use the throttled function:

    import throttle from "lodash.throttle"
    
    const throttledHandleResize = throttle(() => {
            console.log("resizing...");
        }, 200);
    
    window.addEventListener("resize", throttledHandleResize);