小程序节流函数,防止多次点击

在util.js里加入

function throttle(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
        gapTime = 1500
    }
 
    let _lastTime = null
 
    // 返回新的函数
    return function () {
        let _nowTime = + new Date()
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            fn.apply(this, arguments)   //将this和参数传给原函数
            _lastTime = _nowTime
        }
    }
}
module.exports = {
throttle: throttle,
//formatTime: formatTime
}

在引入页面,加入到顶部,引入函数

// pages/zhanbuView/zhanbuView.js
const util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {

在功能调用的地方,例如:

<button bindtap='tap' data-key='abc'>tap</button>

 

const util = require('../../utils/util.js')
 
Page({
    data: {
        text: 'tomfriwel'
    },
    onLoad: function (options) {
 
    },
    tap: util.throttle(function (e) {
        console.log(this)
        console.log(e)
        console.log((new Date()).getSeconds())
    }, 1000)
})

实例:

zhanbuView:util.throttle(function(e){
    
    wx.request({
      
      url: 'https://wwwx.xxxx.xx/Wx/zhanbuView',
      data:{
        yaoId:e.target.dataset.yao,
        author:e.target.dataset.author,
        
      },
      header:{
        'content-type':'application/x-www-form-urlencoded'
      },
      success:(res)=>{

        const app = getApp();
       
            app.globalData.zhanbuViewAuthor=res.data.zhouyiAuthor.name;
            app.globalData.zhanbuViewAuthorInfo=res.data.zhouyiAuthor.info,
          
            app.globalData.zhanbuViewContent=res.data.content,
            app.globalData.zhanbuViewXiang=res.data.xiang,
            //timeline
            app.globalData.zhanbuViewYaoId=res.data.zhouyiYao.id,
         //   console.log(app.globalData.zhanbuViewYaoId),
          //  console.log(app.globalData),
           // console.log(app.globalData.zhanbuYao.data.yaoId),
            wx.redirectTo({
            
              url: '../zhanbuView/zhanbuView',
             
            })
    
    
      }
    })
    //function end 节流函数
      },1500),

 

实测,好用。

posted @ 2020-10-06 11:38  琴声清幽  阅读(207)  评论(0编辑  收藏  举报