0

I was following a tutorial on throttling and this was the code the guy used. However I am unable to understand how the code functions. Shouldn't last be set to zero every time we call throttle?

const throttle = (fn, delay ) => {
    let last = 0
    return (...args) => {
        const now = new Date().getTime();
        if(now-last<delay){
            return;
        }
        last=now; //how does this work - wouldn't last be set to zero the next time the function runs? 
        return fn(...args)
    }   
}
document.getElementById('myid').addEventListener('click',throttle(()=>{
    console.log('you clicked me')
},5000))
questreal
  • 5
  • 1
  • 2
  • 2
    The time you call `throttle` the variable `last` is set to `0`, that's correct but then the return value is another function. In there `last` can change. If you call `throttle` again, you get a *new* and *separate* function with its own `last` variable. The two produced functions share no data. – VLAZ Sep 28 '20 at 17:41
  • Slightly related but still of interest: [JavaScript curry: what are the practical applications?](https://stackoverflow.com/q/113780) – VLAZ Sep 28 '20 at 17:42
  • 2
    I would remark that `throttle` is all about side effects and timers, so not particularly functional. (FP doesn't mean "uses functions") – Bergi Sep 28 '20 at 18:32

0 Answers0