Middle
If debounce is defined as an arrow function, what will change? How to pass arguments using the rest operator (three dots)?
sobes.tech AI
Answer from AI
If debounce is defined as an arrow function, then the this context inside it will be lexically bound to the context in which it was declared. This is convenient to avoid losing the context when passing the function.
Example of debounce as an arrow function with a rest operator for arguments:
const debounce = (func, delay) => {
let timeoutId;
return (...args) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func(...args);
}, delay);
};
};
// Usage:
const log = (...args) => console.log(...args);
const debouncedLog = debounce(log, 300);
debouncedLog('Hello', 'world');
Here, (...args) is a rest operator that collects all passed arguments into an array called args. Then, func(...args) spreads this array back into a list of arguments when calling the original function.