防抖和节流

101 阅读1分钟

一、防抖和节流的应用场景

函数防抖和节流,都是控制事件触发频率的方法。应用场景有很多,输入框持续输入,将输入内容远程校验、多次触发点击事件、onScroll等等。

二、防抖

当持续触发事件的时候,函数是完全不执行的,等最后一次触发结束的一段时间之后,再去执行。

function debounce(func, delay){ 
  let timeout = null
  return function() { // 点击时会调用这个闭包
    clearTimeout(timeout)
    //使用apply是为了让func的this跟闭包一样,如果func是箭头函数apply无效
    timeout = setTimeout(() => { func.apply(this, arguments) }, delay) } 
}
let debounced = debounce(function(){
  console.log('hi')
}, 1000)
document.getElementById("btn").onclick = debounced 

三、节流

节流的意思是让函数有节制地执行,而不是毫无节制的触发一次就执行一次。持续触发时,隔一段时间执行一次。

function throttle(fn, delay){
     let canUse = true
     return function(){
         if(canUse){
             fn.apply(this, arguments)
             canUse = false
             setTimeout(()=>canUse = true, delay)
         }
     }
 }

 const throttled = throttle(()=>console.log('hi'))
 throttled()
 throttled()

tips: 由setTimeout()调用的代码运行在与所在函数完全分离的执行环境上。这会导致,这些代码中包含的 this 关键字在非严格模式会指向 window (或全局)对象,严格模式下undefined。