myTest532 myTest532
myTest532 myTest532

Reputation: 2381

JavaScript Throttle always returning function

I'm trying to understand JavaScript Throttling. I implemented a very basic throttle for the knowledge that I have so far.

const display = (msg) => {
    return msg;
}

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

for(let i=1; i<=5; i++) {
    setTimeout(() => {
        const result = throttleDisplay(display("Hi"), 6000); 
        console.log(result)
    }, i*1000);
}

My console.log is returning [Function] instead of the message Hi. Also, it is returning [Function] 5 times. Shouldn't it ignore the next call until the limit, 6000ms, has passed?

Thanks a lot!

Upvotes: 0

Views: 1311

Answers (1)

trincot
trincot

Reputation: 350272

Throttling works differently.

First, you should name your throttle function just throttle, as it is not specifically linked with display. Then, you should call this throttle to get a function that is specific to display. And only then you would use that secondary function in the actual use case you have for it, i.e. with the timer.

Here is your code corrected:

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

const throttleDisplay = throttle(() => console.log("Hi"), 6000);

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

Upvotes: 2

Related Questions