微信小程序中用TS实现函数节流

前言:我的项目中有一个需求需要用到函数节流,但是发现小程序中节流函数总是不生效,经过一番思考想到了下面的方法。

一,对于用JS开发的小程序

1. 首先直接定义节流函数

2. 然后关键的一步, 在生命周期钩子里初始化节流函数

Page({
data: {
num: 0
},
onLoad: function() {
this.throttle = this.throttle(1000) // 初始化节流函数
  },
/**
* 节流函数
*/
throttle(time) {
let timeOut = null;
return () => {
if(timeOut) {
console.log(‘触发节流,不执行回调‘);
clearTimeout(timeOut);
}
timeOut = setTimeout(() => {
this.addNum()
}, time);
}
},
/**
* 被节流函数
**/
addNum() {
this.setData({
num: this.data.num + 1
})
console.log(`延迟 1 秒执行回调 ${this.data.num}`);
},
})

效果:

二,对于用TS开发的小程序

ts写的小程序实现函数节流和js小程序略有不同,ts必须用 class 的方式实现, 下面我就用自己项目中的案例来展示

1. 创建节流函数类

2. 在页面生命周期里初始化类

3. 在目标函数里调用类的静态方法--节流函数

export class Throttle {
static timeOut: any = null
static callback: any = null
public static init(callback, time) {
this.callback = callback
this.timeOut = time
}
public static search(detail) {  // 这里的 detail 是为了接收页面传过来的数据
this.timeOut as any
clearTimeout(this.timeOut);
this.timeOut = setTimeout(() => {
this.callback(detail)
}, 400);
}
}
onLoad() {
Throttle.init(this.uploadData, 400) // 初始化 
}
onSearch({ detail }) {  // detail 是页面传过来的数据,不需要的可以删掉
Throttle.search(detail) // 调用节流函数
},

我这个需求是搜索功能的节流,经验证也是可以的。

总结: 函数节流的实现方法比较多,这里的例子使用的是最简单的,其他请各位自行搜索吧。

微信小程序中用TS实现函数节流

原文:https://www.cnblogs.com/weiyongchao/p/14482631.html

以上是微信小程序中用TS实现函数节流的全部内容。
THE END
分享
二维码
)">
< <上一篇
)">
下一篇>>