防抖

js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
function debounce(fn, delay) {
  let timer;
  return function (...args) {
    timer && clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

// 测试
function task(arg) {
  console.log("run task" + arg);
}
const debounceTask = debounce(task, 1000);
window.addEventListener("scroll", () => debounceTask(11));

节流

js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
function throttle(fn, delay) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last < delay) return;
    last = now;
    fn.apply(this, args);
  };
}

// 测试
function task() {
  console.log("run task");
}
const throttleTask = throttle(task, 1000);
window.addEventListener("scroll", throttleTask);