微信小程序 防连点时间

阅读: 评论:0

微信小程序 防连点时间

微信小程序 防连点时间

场景

在使用小程序的时候会出现这样一种情况:当网络条件差或卡顿的情况下,使用者会认为点击无效而进行多次点击,最后出现多次跳转页面的情况,就像下图(快速点击了两次):

解决办法

然后从 轻松理解JS函数节流和函数防抖 中找到了解决办法,就是函数节流(throttle):函数在一段时间内多次触发只会执行第一次,在这段时间结束前,不管触发多少次也不会执行函数。

/utils/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()

_lastTime = _nowTime

}

}

}

throttle: throttle

}

/pages/throttle/throttle.wxml:

tap

/pages/throttle/throttle.js

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)

})

这样,疯狂点击按钮也只会1s触发一次。

但是这样的话出现一个问题,就是当你想要获取this.data得到的this是undefined, 或者想要获取微信组件button传递给点击函数的数据e也是undefined,所以throttle函数还需要做一点处理来使其能用在微信小程序的页面js里。

出现这种情况的原因是throttle返回的是一个新函数,已经不是最初的函数了。新函数包裹着原函数,所以组件button传递的参数是在新函数里。所以我们需要把这些参数传递给真正需要执行的函数fn。

最后的throttle函数如下:

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

}

}

}

再次点击按钮this和e都有了:

参考

源代码

本文发布于:2024-02-01 17:10:48,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170677866738180.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:连点   时间   程序   微信小
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23