JS 防抖和节流的函数应用

1. 防抖函数


    




2. 节流函数的应用

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

// 示例用法:
function logThrottled() {
  console.log("节流函数触发了!");
}

const throttledFunction = throttle(logThrottled, 1000);

// 当需要节流的事件触发时,调用 throttledFunction
// 例如,滚动事件触发节流效果:
window.addEventListener("scroll", throttledFunction);

时小记,终有成。

你可能感兴趣的:(javascript,前端)