微信小程序开发专题微信小程序真香小程序

小程序中使用函数节流解决用户频繁点击造成多次响应

2019-08-29  本文已影响0人  编程小橙子
timg.jpg

小程序防止用户多次点击解决方案【使用函数节流throttle】

频繁的点击按钮,会出现多次的响应问题,可以采取函数节流 throttle的方式去解决该问题

1.error 示例图


image.png

2.看看success的示例图以及代码


image.png
3.首先在该项目所对应的页面中新建一个public.js脚本
public.js
module.exports = {
  throttleFunc: function throttleFunc(func, marginTime) {
    if (marginTime == undefined || marginTime == null) {
      marginTime = 1700
    }
    let lastTime = null
    return function () {
      let currentTime = + new Date()
      if (currentTime - lastTime > marginTime || !lastTime) {
        func.apply(this, arguments)
        lastTime = currentTime
      }
    }
  },
}

4.在throttle.wxml中添加一个点击事件

<!--pages/throttle/throttle.wxml-->
<view class="container">
  <button type="primary" style="width:100%" bindtap="handleAdd">点击</button>
</view>

5.引入public.js脚本并且在点击事件中进行使用

// pages/throttle/throttle.js
var common = require("../throttle/public.js")  //引入public.js脚本
Page({
  /**
   * 页面的初始数据
   */
  data: {
    index:0
  },
  // 用户触发点击事件
  handleAdd: common.throttleFunc(function(e){
    var that = this
    var index = that.data.index
    that.setData({
      index: index+1
    })
    console.log(index)
    wx.navigateTo({
      url: '/pages/tel/tel',
    })
  },1000),
})

通过上述的函数节流方式就可以解决用户频繁点击按钮导致触发多次点击以及相应多次的问题。

喜欢作者的小朋友可以给个小鸡腿,后期还会不断更新新的内容给大家

上一篇下一篇

猜你喜欢

热点阅读