求教节流与防抖的实际应用代码?

$("#ul_list").on("click", "li", function(e) {
  //...li指定的列表数据拉取
}

以上代码,如何加以节流、防抖,求代码及说明!!!感谢!!!

阅读 2.8k
2 个回答

节流

function throttle(func, delay) {
  let timeoutId;
  return function(...args) {
    if (!timeoutId) {
      func.apply(this, args);
      timeoutId = setTimeout(() => {
        timeoutId = null;
      }, delay);
    }
  };
}

$("#ul_list").on("click", "li", throttle(function(e) {
  // ... li指定的列表数据拉取
}, 300)); // 延迟 300 毫秒执行一次

防抖

function debounce(func, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

$("#ul_list").on("click", "li", debounce(function(e) {
  // ... li指定的列表数据拉取
}, 300)); // 延迟 300 毫秒执行,若期间有新事件则重新计时
新手上路,请多包涵

$("#ul_list").on("click", "li", debounce(function(e) {
//...li指定的列表数据拉取
}))
debounce--防抖节流方法

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题