JavaScript · Senior · Question 25 of 75
Why is it important to preserve this and arguments in a debounce implementation?
function debounce(fn, ms) {
let t;
return function (...args) {
clearTimeout(t);
t = setTimeout(() => fn.apply(this, args), ms);
};
}- ✓Correct answer: Otherwise the wrapped method loses the object's context and call parameters
- 2Otherwise the previous timer can't be cleared via
clearTimeout - 3Otherwise the function runs synchronously, without the
msdelay
Explanation
The wrapper must be transparent: calling obj.save(data) through debounce has to reach fn with the same this and arguments. That's why a regular function is returned (it has its own this), and inside the timer an arrow preserves it.