小程序中使用防抖函数能够更加简单

通常小程序绑定事件以下
<view class="create-page" bindtouchmove="debounceImageMoveIng" bindtouchend="imageMoveEnd">小程序

而正常绑定事件使用防抖函数时须要初始化防抖函数
jQuery(window).on('resize', \_.debounce(calculateLayout,150));浏览器

咱们知道防抖函数是一个函数定义一个timer属性,而后返回一个闭包函数,当你调整浏览器大小或者滚动页面时,执行当就是防抖函数返回的这个闭包函数,而防止频繁执行就是经过timer+setTimeout控制。闭包

function debounce(fn,wait){
    var timer = null;
    return function(){
        if(timer !== null){
            clearTimeout(timer);
        }
        timer = setTimeout(fn,wait);
    }
}
    
function handle(){
    console.log(Math.random());
}
    
window.addEventListener("resize",debounce(handle,1000));

在小程序中若是用 this.timer 代替闭包的timer 那么就不须要额外的闭包函数,也不须要初始化防抖函数。dom

debounceImageMoveIng: function (e) {
    if(this.timer) {
      clearTimeout(this.timer)
    }
    this.timer = setTimeout(()=>{
      this.imageMoveIng(e)
    },10)
  }

错误使用防抖函数的例子函数

debounceImageMoveIng: function (e) {
    // 错误:每次触发事件都只是初始化
    debounce(()=>{
      this.imageMoveIng(e)
    },10)
    // 错误:每次触发事件初始化后 都执行,至关于了每次都延迟执行
    debounce(this.imageMoveIng,10)(e)
  }
相关文章
相关标签/搜索