首页 > 微信 > 详细

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

时间:2021-03-04 23:17:29      阅读:218      评论:0      收藏:0      [点我收藏+]

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

一,对于用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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!