手写通俗易懂版的防抖与节流

185 阅读1分钟

什么是防抖与节流?

防抖(debounce): 所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。节流会稀释函数的执行频率。

一句话总结,若时间周期为5秒,防抖是5秒内重复的触发会导致重新计时,直到5秒内没有重复触发函数才会执行,节流是5秒内只会执行第一次触发的函数,重复的触发无效。

代码

防抖:

function debounce(fn, wait) {
    let timer = null;
    return function () {
      let context = this;
      let args = arguments;
      //当timer存在的时候我先删除上一个定时器之后重新计算函数执行事件
      if (timer) {
        clearTimeout(timer);
      }
      
      timer = setTimeout(() => {
        fn.apply(context, args)
      }, wait);
    }
  }

节流:

function throttle(fn, delay) {
    let timer;
    return function () {
        let _this = this;
        let args = arguments;
        //在一段时间内你只能执行一次,假如上面一个定时器内函数并未执行,你这次触发的将不执行,直到上一个执行完之后给timer = null
        if (timer) {
            return;
        }
        timer = setTimeout(function () {
            fn.apply(_this, args);
            timer = null; 
            // 在delay后执行完fn之后清空timer,此时timer为假,throttle触发可以进入计时器
        }, delay)
    }
}