美文网首页
微信小程序防抖、节流的使用

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

作者: 今天也要努力好吗 | 来源:发表于2021-03-13 11:04 被阅读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),
    })
    

    相关文章

      网友评论

          本文标题:微信小程序防抖、节流的使用

          本文链接:https://www.haomeiwen.com/subject/ywnjqltx.html