The problem of continuous page jump caused by multiple trigger events of the WeChat applet and the solution

Recently, in the development process of small programs, when the network conditions are poor or freezes, most users will think that the click is invalid and click multiple times, and finally there will be multiple jumps or even a loop of jumps.

Finally, after many times of review and the introduction of the official documentation of the WeChat applet:

It takes a certain amount of time for the page to jump, and the event that triggers the jump may occur multiple times before the jump is completed.

After breakpoint debugging, it can be seen from the debugging record that multiple or even continuous events are triggered, resulting in multiple or circular jumps.

The above problems can be solved by function throttling and function anti-shake in JS .

For example, as shown in the figure below: During the development process, similar problems frequently occur on the tab page on the real machine

The specific solution is as follows:

Use function throttling (throttle): The function will only be executed for the first time when it is triggered multiple times within a period of time. Before the end of this period, no matter how many times it is triggered, the function will not be executed.

/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.apply(this, arguments)   //将this和参数传给原函数
          _lastTime = _nowTime
      }
  }
}
module.exports = {
  throttle: throttle
}

fn.apply(this,arguments) in the above util.js file is to copy the properties and methods of the function (mainly pass this and parameters to the original function), mainly to implement class inheritance.

Prevent this.data from being undefined, or want to get the data e of the click function is also undefined

/pages/xx-list/xx-list.wxml:

  <view data-current="0" bindtap="swichNav" data-current="0">11</view>

/pages/xx-list/xx-list.js:

const util = require('../../utils/util.js')

Page({
    data: {
        
    },
    onLoad: function (options) {

    },
    swichNav: util.throttle(function (e) {
        console.log(this)
        console.log(e)
    }, 1000),
})

The above code can solve the problem of continuous page jump.

If you have a better way, please share it.

Guess you like

Origin blog.csdn.net/jianshou6442/article/details/113558733