微信小程序:防止屡次点击跳转(函数节流)

场景

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

解决办法

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

/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
        }
    }
}

module.exports = {
  throttle: throttle
}

/pages/throttle/throttle.wxml:微信小程序

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

/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获得的thisundefined, 或者想要获取微信组件button传递给点击函数的数据e也是undefined,因此throttle函数还须要作一点处理来使其能用在微信小程序的页面js里。app

Screen Shot 1

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

最后的throttle函数以下:ui

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
        }
    }
}

再次点击按钮thise都有了:
Screen Shot 2this

参考

源代码

相关文章
相关标签/搜索