### [小程序使用函数节流解决页面多次跳转问题](https://www.prosaas.cn/article/16698) **Published:** 2020-05-05T01:27:28 **Author:** 5201314 **Excerpt:** 本篇文章给大家介绍一下小程序使用函数节流解决页面多次跳转问题。有一定的参考价值,有需要的朋友可以参考一下,希望… 本篇文章给大家介绍一下小程序使用函数节流解决页面多次跳转问题。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。 ![](https://img.php.cn/upload/article/000/000/024/5eb0c0cdcbbf3426.jpg) 在使用小程序的时候会出现这样一种情况:当网络条件差或卡顿的情况下,使用者会认为点击无效而进行多次点击,最后出现多次跳转页面的情况,这个问题可以通过**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里。 ![](https://img.php.cn/upload/image/865/126/496/1588641849241388.jpg) 出现这种情况的原因是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都有了: ![](https://img.php.cn/upload/image/549/803/359/1588641894709803.jpg) 推荐:《小程序开发教程》 以上就是小程序使用函数节流解决页面多次跳转问题的详细内容,更多请关注知企PROSAAS其它相关文章! **Categories:** 后端开发 ---