当前位置:网站首页>Wechat applet: prevent multiple click jump (function throttling)

Wechat applet: prevent multiple click jump (function throttling)

2020-11-06 01:22:00 :::::::

scene

When using applets, there is a situation like this : When network conditions are poor or stuck , Users will think that the click is invalid and make multiple clicks , Many times the page jumps , As the figure below ( Two quick clicks ):

terms of settlement

And then from Easy to understand JS Function throttling and function buffeting We found a solution , Namely Function throttling (throttle): A function that fires multiple times over a period of time will only execute the first time , By the end of this period , No matter how many times it is triggered, it will not execute the function .

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

such , Crazy click on the button will only 1s Trigger once .

But then there's a problem , It's when you want to get this.data Got this yes undefined, Or want to get wechat components button Data passed to the click function e It's also undefined, therefore throttle Function also needs to do some processing to make it can be used in the wechat applet page js in .

The reason for this is throttle It returns a new function , It's not the original function anymore . The new function encapsulates the original function , So the component button The parameters passed are in the new function . So we need to pass these parameters to the functions that really need to be executed fn.

final throttle Function as follows :

function throttle(fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
        gapTime = 1500
    }

    let _lastTime = null

    //  Return the new function 
    return function () {
        let _nowTime = + new Date()
        if (_nowTime - _lastTime > gapTime || !_lastTime) {
            fn.apply(this, arguments)   // take this And parameters to the original function 
            _lastTime = _nowTime
        }
    }
}

Click the button again this and e Have it all. :

Reference resources

Source code

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[:::::::]所创,转载请带上原文链接,感谢