首页 > 解决方案 > Javascript 中的去抖动不适用于车轮事件

问题描述

我正在尝试使用去抖动功能来限制调用的滚动事件的数量。

我不知道为什么这根本不起作用......

有任何想法吗?

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

标签: javascriptdebounce

解决方案


wheel它在每个事件上创建去抖动功能。首先对函数进行去抖动,然后将其放入事件侦听器中。

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


推荐阅读