防抖和节流简版

199 阅读1分钟

话不多说直接上代码

防抖

防抖是一段时间内是否重复触发,如果重复触发就重新开始计算时间

function debounce(fn, delay) {
   let timer; // 维护一个 timer
   return function () {
       let _this = this; // 取debounce执行作用域的this
       let args = arguments;
       if (timer) {
          clearTimeout(timer);
        }
        timer = setTimeout(() => {
             fn.apply(_that, args); // 用apply指向调用debounce的对象,相当于this.fn(args);
        }, delay);
   };
 }

节流

节流是一段时间内只会执行一次

 function throttle(fun, delay) {
   let timer;
   let last = 0;
   return function () {
     let _that = this;
     let args = arguments;
     let now = +new Date();
     if(now - last > delay) {
       last = now;
       fun.apply(_that, args);
     }
   }
 }

经过测试后可以应对基本情况

var btn = document.getElementsByClassName("btn")[0];
btn.addEventListener("click", () => { test() })
function test() {
	console.log(123)
}
 var test = throttle(test, 1000);

20200708230700776.png