https://www.html.cn/archives/6589/

throttle节流

一个函数在大于设定的执行周期后,才会再次执行

  • 性能能优化角度,在规定的时间内,函数第一次执行有效,后面的无效
  • 第一次有效

  • Button的疯狂点击,例如秒杀的抢购

  • resize窗口调整
  • scroll 页面滚动
  • DOM的拖拽功能

函数节流用 Date.now实现,求时间差值

  1. throttle(callback, wait)
  2. export function throttle(callback, timeout) {
  3. let startTime = 0;
  4. return (...args) => {
  5. let nowTime = Date.now();
  6. // 第一次会执行,后面 startTime = nowTime
  7. if(nowTime - startTime >= timeout) {
  8. callback.call(this, ...args);
  9. startTime = nowTime;
  10. }
  11. }
  12. }

节流函数,在 wait 毫秒内最多执行 callback 一次

debounce防抖

频繁触发事件,在规定的时间内,只会执行最后一次,前面的不执行

  • 最后一次有效
  • input
  • scroll
  • keyup, keydown, keypress

函数防抖,用定时器实现

  1. debounce(callback, wait)
  2. debounce(() => {}, 1000)
  3. export function debounce(callback, timeout = 500) {
  4. let timer = null;
  5. return (...args) => {
  6. if(timer !== null) clearTimeout(timer);
  7. timer = setTimeout(() => {
  8. callback.call(this, ...args);
  9. timer = null; // 执行完之后,重置timer
  10. }, timeout);
  11. }
  12. }

防抖函数会从上一次被调用后,延迟 wait 毫秒后调用 callback