# 防抖

    // 防抖
function debounce(fn, wait) {
  let timer = null;

  return function () {
    if (timer) {
      // 如果存在定时器,则重新计时,因为此时还没有到我们设置的时间
      // 比如设置1s, 现在是0.5s
      // 所以重新计时,开始新的1s周期,等1s周期到了再执行我们的函数
      // 我们是想要定时器来控制代码执行
      clearTimeout(timer);
      timer = null;
    }

    timer = setTimeout(() => {
      fn(...arguments);
    }, wait);
  };
}
// test
const debounceRun = debounce(() => {
  console.log(123);
}, 1000);
window.addEventListener("mousemove", debounceRun);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 节流

# 定时器

var throttle = function (fn, delay) {
  let timer = null;
  return function () {
    if (!timer) {
      timer = setTimeout( () => {
        fn(...arguments);
        timer = null;
      }, delay);
    }
  };
};
1
2
3
4
5
6
7
8
9
10
11

# 时间戳

var throttle = function (fn, delay) {
  let pre = Date.now();
  return function () {
    let now = Date.now();
    if (now - pre >= delay) {
      fn(...arguments);
      pre = now;
    }
  };
};
1
2
3
4
5
6
7
8
9
10