防抖与节流

防抖

指触发事件后在n秒内函数只能执行一次,如果在n秒内又触发了事件,则会重新计算函数执行时间。

    document.getElementById('btn').onclick = debounce(function(e){
      console.log(e); // MouseEvent 
      console.log(this) //<button id="btn">点击</button>
    }, 1000);

    // 通过定时器
    function debounce(fn, wait) {
      let timmer = null;
      return function (...arg) {
        const now = !timmer;
        clearTimeout(timmer);
        timmer = setTimeout(() => {
          timmer = null;
        }, wait)
        if(now) {
          fn.apply(this, arg);
        }
      }
    }

节流

指连续触发事件但是在一段时间中只执行一次函数。

   document.getElementById('btn').onclick = jl(function(e){
     console.log(e); // MouseEvent 
     console.log(this) //<button id="btn">点击</button>
   }, 1000);
   
   // 通过定时器
   function jl(fn, wait) {
     let timmer = null;
     return function (...arg){
       if(!timmer) {
         timmer = setTimeout(()=>{
           clearTimeout(timmer);
           timmer = null;
           fn.apply(this, arg);
         }, wait);
       }
     }
   }

   // 通过时间戳
   function jl(fn, wait) {
     let last = 0;
     return function (...arg){
       const now = Date.now();
       if(now - last > wait) {
         fn.apply(this, arg);
         last = now;
       }
     }
   }
原文地址:https://www.cnblogs.com/wangyong1997/p/13266597.html