JavaScript防抖/节流函数个人总结

136 阅读1分钟

HTML&&CSS

<div id="container"></div>
#container{
        width: 100%; height: 200px; line-height: 200px; text-align: center; color: #fff; background-color: #444; font-size: 30px;
    }

JS

// func.apply(thisArg, [argsArray])
// thisArg:在 func 函数运行时使用的 this 值
let count = 1;
let container = document.getElementById('container');
function getUserAction() {
    console.log(this);
    container.innerHTML = count++;
};
// 防抖函数,总是在用户触发最后一次事件后延迟一定时间执行
function debounce(func,await){
  let timer=null;
  // let context=this;
  // 页面render就会执行到这,此时this指向是Window   
  return function(){
    const context=this;
    const args = arguments;
    // console.log(context,arguments);
    if(timer) clearTimeout(timer);
    // 因为setTimeout是挂载在window对象上的,所以我们需要将this指向正确的对象
    timer=setTimeout(()=>{func.apply(context,args)},await)
  }
}
// 节流函数,每隔一定时间执行一次
function throttle(func,delay){
  let prev=Date.now();
  // console.log(this);
  // 页面render就会执行到这,此时this指向是Window  
  return function(){
    let curr=Date.now();
    const args=arguments;
    if(curr-prev>=delay){
      func.apply(this,args);
      // func();
      prev=Date.now()
    }
  }
}

// container.onmousemove = debounce(getUserAction,1000);
container.onmousemove = throttle(getUserAction,1000);