php两次跳转,小程序使用函数节流解决页面多次跳转问题

本篇文章给大家介绍一下小程序使用函数节流解决页面多次跳转问题。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

456b49f7c55dad82a4e7168265d00e40.png

在使用小程序的时候会出现这样一种情况:当网络条件差或卡顿的情况下,使用者会认为点击无效而进行多次点击,最后出现多次跳转页面的情况,这个问题可以通过JS中的函数节流和函数防抖找到解决方法。

根据官方文档介绍,函数节流就是规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。因此修改.js文件如下:function throttle(fn, gapTime) {

if (gapTime == null|| gapTime == undefined) {

gapTime = 1500

}

let _lastTime = nullreturn function () {

let _nowTime = +new Date()

if (_nowTime -_lastTime > gapTime || !_lastTime) {

fn()

_lastTime =_nowTime

}

}

}

module.exports = {

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((newDate()).getSeconds())

}, 1000)

})

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

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

3e72b941238524e0c1d348cb2f676699.png

出现这种情况的原因是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都有了:

18e42ed93efec35fa48b021be38e682b.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值