export const debounce = (callback: Function, ms = 300) => {
let timeoutId: ReturnType<typeof setTimeout>
return function (...args: any[]) {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => callback.apply(this, args), ms)
}
}
I want to make the debounce function a Util function and use it throughout the project. However, if you make the function that the debounce function returns as an arrow function, a script error occurs. This becomes undefined. Can't the function that the debounce function returns use the arrow function? I'm curious about the reason
export const debounce = (callback: Function, ms = 300) => {
let timeoutId: ReturnType<typeof setTimeout>
return (...args: any[]) => {
clearTimeout(timeoutId)
timeoutId = setTimeout(() => callback.apply(this, args), ms)
}
}
Changing the arrow function to a returning code in this way causes an error. I'm curious about the reason
.this inside arrow function will resolve lexically, meaning that value of this does not depend on call-site(where the function is being called), but instead it depends on the function outer scope(defined when writing code) - basically meaning it will take this lexically from the outer scope (eg: outer function or window object). And that is why there is no sense to use arrow with apply in order to modify this.