JS debounce 实现原理

4 min read

JS debounce 实现原理

const debounce = (func, delay) => {
  let timeout;
  return (...param) => {
    if (timeout) {
      clearTimeout(timeout);
    }
    timeout = setTimeout(function() {
      func(...param);
    }, delay);
  }
}
const log = debounce(() => console.log('call'), 5000)
log()
log()
log()

debounce 原理讲解:

0s ---------> 1s ---------> 2s --------> ...

一定要理解:这三个函数都是同步操作,所以它们都是在 0~1s 这个时间段内瞬间完成的;

​ log()#1 // timeout#1
​ log()#2 // 发现 timeout#1!取消之,然后设置timeout#2
​ log()#3 // 发现 timeout#2! 取消之,然后设置timeout#3
// 所以,log()#3 结束后,就只剩timeout#3在独自等待了