【小程序】节流函数与防抖函数

节流防抖两者均在性能优化上起到一定的作用,但实质上又不完全相同。

1.什么是 节流

节流是减少函数的触发频率。
应用场景:输入框等。

2.什么是 防抖

防抖 是延迟函数执行,且不管触发多少次都只执行最后一次。
应用场景:比如窗口调整、页面滚动、抢购和疯狂点击等。

3. 防抖节流 要怎样用到小程序中呢?

在微信小程序中,我们回把方法封装到公共函数库当中。

// utils/util.js
// 节流函数
function throttle(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
        gapTime = 1000
    }
    let _lastTime = null
    return function (e) {
        let _nowTime = +new Date()
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            fn(this,e)
            _lastTime = _nowTime
        }
    }
};
// utils/util.js
// 防抖函数
function debounce(fn, interval) {
    var timer;
    var gapTime = interval || 1000;//间隔时间,如果interval不传,则默认1000ms
    return function(e) {
      clearTimeout(timer);
      timer = setTimeout(function() {
        fn(this,e)
      }, gapTime);
    };
  }

export default {
  throttle,
  debounce
};

调用的话

// xxx.wxml 文件中
<view class="left dis_flex_mid">
	<image bindtap=" throttle_test" data-test="6" src="https://www.douban.com/group/topic/250660432/?_i=5394726DaFyZV3"></image>
	<image bindtap=" debounce_test" data-test="8" src="https://www.douban.com/group/topic/250660432/?_i=5394726DaFyZV3"></image>
</view>
// xxx.js文件中
 // throttle 节流测试
	throttle_test:util.throttle((that,e)=>{
        console.log('节流测试--that--',that)
        console.log('节流测试--e--',e)
    }),
    
 // debounce 防抖测试
	debounce_test:util.debounce((that,e)=>{
        console.log('防抖测试--that--',that)
        console.log('防抖测试--e--',e)
    }),


tips 使用封装后,我们的thise的指向发生了变化,此时需要‘摆正’我们this和e。网上很多人说用 fn.apply(this, arguments) 或者 fn.call(this, arguments)就可以摆正,但经我亲测发现,this的指向还不是我想要的。最后,用到了 fn(this,e) 就ok了~

猜你喜欢

转载自blog.csdn.net/zxsy19966/article/details/127248855
今日推荐