以下是一个基于时间戳的节流函数的示例代码:

function throttle(func, delay) {
  let lastTime = 0;
  return function(...args) {
    const currentTime = Date.now();
    if (currentTime - lastTime >= delay) {
      func.apply(this, args);
      lastTime = currentTime;
    }
  };
}

// 示例用法
function handleScroll() {
  console.log('Scroll event handled');
}

const throttledHandleScroll = throttle(handleScroll, 1000);
window.addEventListener('scroll', throttledHandleScroll);

上面的代码定义了一个throttle函数,它接受一个函数和一个延迟时间作为参数。返回一个新的函数,该新函数在每个延迟时间内只能被调用一次。

在示例用法中,我们定义了一个handleScroll函数,并使用throttle函数创建了一个节流后的函数throttledHandleScroll。然后,我们将throttledHandleScroll作为滚动事件的处理程序,以确保滚动事件每隔1秒只能被处理一次。

JavaScript 节流函数代码示例:限制事件触发频率

原文地址: https://www.cveoy.top/t/topic/qqDD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录