Just title says. Most throttle approaches in javascript require some sort of a variable to store the timer or setTimeout id to determine if a function is to be cancelled or not. However im having some difficulty in wrapping into my head on how do I exactly write this function in functional way.
const throttle = (func) => {
let handler = null;
return (...args) => {
if (handler === null) {
handler = setTimeout(() => {
handler = null
}, 2000)
return func(...args)
} else {
return null
}
}
}
In this code, It seems to break the rules of avoiding side effects
since the return function is mutating the variable inside the throttle scope. How do I exactly convert this logic into a pure function(s)?