防抖与节流

吐槽君 分类:javascript

前提: 我们不希望一个事件被高频触发执行函数, 所以就有了防抖和节流

一、防抖

触发一个事件几秒后,去执行函数,如果在几秒内再次触发事件,则会重新计算函数的执行时间

    触发事件后 非立即执行的防抖函数:
    
    function debounce(func, wait){
        let timeout
        return function () {
            const this_ = this
            const args = [...arguments]
            if(timeout) clearTimeout(timeout)
            timeout = setTimeout(() => {
                func.apply(this_, args)
            }, wait)
        }
    }
    
    触发事件后 立即执行函数:
    
    function debouce(){
        let timeout
        return function () {
            const this_ = this
            const args = [...arguments]
            if(timeout) clearTimeout(timeout)
            let callNow = !timeout
            timeout = setTimeout(() => {
                timeout = null
            }, wait)
            if(callNow) func.apply(this_, args)
        }
    }
    
    
    注意: 函数中用到apply,是为了debounce中返回的函数this指向不变,且能使用到e参数
    
 

二、节流

事件在频繁触发的过程中,函数只在几秒内执行一次,执行间隔是一样的,相当于稀释事件触发, 与防抖不同,不会重新计算执行时间

   时间戳版(时间到后会立即执行):
   
   function throttle(func, wait){
       var previous = 0
       return function () {
           let now = new Date()
           let this_ = this
           let args = [...arguments]
           if(now -previous > wait){
               func.apply(this_, args)
               previous = now
           }
       }
   }
   
   
   定时器版:
   
   function throttle(func, wait){
       let timeout
       return function() {
           let context = this;
           let args = arguments;
           if (!timeout) {
               timeout = setTimeout(() => {
                   timeout = null;
                   func.apply(context, args)
               }, wait)
           }
      }
}


轻易的发现,两个版本的区别在于,前者事件触发是在时间段开始的时候,后者是在时间段内结束的时候
   
   
   
 

作者:掘金-防抖与节流

回复

我来回复
  • 暂无回复内容