Skip to content

My throttle function is not waiting the limit time

I’m learning throttling and I’m having an issue where my throttle method is not waiting the limit time to run.

const display = (msg) => {
    console.log(msg). // I know this function does not do anything, but I'm trying to understand how I can call a function inside my throttle.
}

const throttle = (func, limit) => {
    let flag = true;
    return function() {
        if(flag) {
            func.apply(this, arguments);
            flag = false;
            setTimeout(() => flag = true, limit);
        }
    }
}

const throttleDisplay = () => {
    return throttle(display("Hi"), 6000);
}

for(let i=1; i<=10; i++) {
    setTimeout(throttleDisplay, i*1000);
}

My output is “Hi” 10 times, but I shouldn’t have 10 times Hi because I have a 6s wait between one call and another.

Answer

throttle takes a callback as a parameter, but you’re invoking display immediately.

const throttleDisplay = () => {
    return throttle(display("Hi"), 6000);
}

is exactly equivalent to

const throttleDisplay = () => {
    const result = display("Hi");
    return throttle(result, 6000);
}

See the problem?

You need a function that invokes display with the argument you want instead:

const throttleDisplay = () => {
    return throttle(() => display("Hi"), 6000);
}