微信小程序防抖、节流的使用

2021-03-13  本文已影响0人  今天也要努力好吗

1、防抖、节流函数的封装

在utils文件夹下新建utils.js文件,然后写入节流和防抖函数

const throttle=(fn,wait)=> {//节流
  var prev=Date.now();
  return function () {
    var context=this;
    var args=arguments;
    var now=Date.now();
    console.log(now-prev>wait)
    if(now-prev>wait){
      fn.apply(context,args)
      prev=Date.now()
    }
  }
}
const debounce=(func, wait)=>{//防抖
  // wait:500ms;func:被频繁触发的事件
  let timeout;
  return function () {
    let context = this;
    let args = arguments;
    let later = () => {
      timeout = null;
      func.apply(context, args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  }
}

module.exports = {
  throttle, debounce
}

在.js页面引入并使用:

var utils=require('../../../utils/util');
Page({
btnNext:utils.throttle(function(e) {
    this.nextpage()
  },500),
  btnPrev:utils.throttle(function(e) {
    this.prevpage()
  },500),
})
上一篇下一篇

猜你喜欢

热点阅读