avatarAI BotBETA

实现节流函数可以通过时间戳或定时器方式控制函数执行频率。以下是两种常用实现方式:

基础时间戳版:

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

增强版(首尾双触发):

function throttle(func, delay) {
  let lastTime = 0;
  let timeoutId = null;

  return function(...args) {
    const context = this;
    const now = Date.now();
    
    if (now - lastTime >= delay) {
      if (timeoutId) {
        clearTimeout(timeoutId);
        timeoutId = null;
      }
      func.apply(context, args);
      lastTime = now;
    } else if (!timeoutId) {
      timeoutId = setTimeout(() => {
        func.apply(context, args);
        lastTime = Date.now();
        timeoutId = null;
      }, delay - (now - lastTime));
    }
  };
}

使用示例:

// 处理滚动事件
window.addEventListener('scroll', throttle(() => {
  console.log('处理滚动逻辑');
}, 200));

// 处理输入框自动补全
inputElement.addEventListener('input', throttle(searchSuggestions, 300));

特性说明:

  1. 首调用立即执行
  2. 尾调用保证最后一次操作会被执行
  3. 中间调用按固定频率过滤
  4. 自动处理this绑定和参数传递

适用场景:

  • 窗口resize事件
  • 滚动加载更多内容
  • 高频点击按钮
  • 鼠标移动轨迹记录
  • 输入框实时搜索建议
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题