Debouncing in Javascript not working with wheel event

Viewed 1337

I'm trying to use a debounce function to limit the number of scroll events called.

I'm not sure why this isn't working at all...

Any ideas?

window.addEventListener('wheel', () => {
  debounce(scrollSection, 300);
});

const scrollSection = () => {
  console.log(1);
}

const debounce = function(fn, d) {
  let timer;
  return function() {
    let context = this;
    let args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, d);
  }
}
1 Answers

it creates debounced function on every wheel event. Debounce a function first, then put it into event listener.

window.addEventListener('wheel', debounce(scrollSection, 300));

const scrollSection = () => {
  console.log(1);
}

const debounce = function(fn, d) {
  let timer;
  return function() {
    let context = this;
    let args = arguments;
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(context, args);
    }, d);
  }
}

Related