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);
  };
}

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.

Further reading

Problem with a question

JavaScript · Senior · question 25

Test yourself

Take the JavaScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz