小程序 节流搜索Throttle(使用SetTimeout实现的)

基础实现

每次用户输入,或者点击搜索按钮,都调用throttleSearch()函数。
throttleSearch函数内部,每次都会取消上一次定时,并且开启新定时。
这就确保了,短时间内的连续多次调用,仅有最后一次调用生效。

  data: {
    inputValue: "",
    timeoutID: null, //timeout编号
  },


    throttleSearch() {
      //清除旧timeout
      if (this.data.timeoutID != null) {
        clearTimeout(this.data.timeoutID);
      }

      //延迟1秒无输入才触发搜索
      var timeoutID = setTimeout(() => {
        this.triggerEvent('search', this.data.inputValue)
      }, 1000);

      //存储新的timeoutID
      this.setData({
        timeoutID: timeoutID
      })
    }

实际代码示例(根据项目需求又做了点改进,可以设置延迟时间)

(以下是小程序自定义搜索框组件的js代码。关键查看 throttleSearch(delayms) 函数 )

/*
  输入文字、点击搜索框、删除搜索文字,都是触发 "search"来回调。
【删除的回调,是空字符串】
使用示例:
    <plain-searchbar autoSearch='true' search="{{search}}" 
    hint="请输入订单号搜索" bind:search="search"></plain-searchbar>
 */

Component({
  properties: {
    hint: {
      type: String,
      value: "搜索"
    },
    autoSearch: { //是否输入文字自动触发搜索
      type: Boolean,
      value: true
    }
  },
  data: {
    inputValue: "",
    timeoutID: null, //timeout编号
  },
  methods: {
    //用户点击确定
    handleConfirm() {
      this.throttleSearch(0)
    },
    //用户输入
    handleInput(e) {
      this.setData({
        inputValue: e.detail.value
      })
      if (this.properties.autoSearch) {
        this.throttleSearch(1000)
      }
    },
    // 点击清空输入框icon
    handleDeleteClick: function () {
      this.setData({
        inputValue: ''
      })

      this.throttleSearch(0)
    },
    //节流搜索。确保了,短时间内的连续多次调用,仅有最后一次调用生效。
    //delayms等待多少毫秒才搜索。如果需要立即搜索,则设置为0.
    //在等待时间里面,再次调用,则会取消上次等待的任务,并开始新的等待。
    throttleSearch(delayms) {
      //请求旧timeout
      if (this.data.timeoutID != null) {
        clearTimeout(this.data.timeoutID);
      }

      //延迟1秒无输入才触发搜索
      var timeoutID = setTimeout(() => {
        this.triggerEvent('search', this.data.inputValue)
      }, delayms);

      //存储新的timeoutID
      this.setData({
        timeoutID: timeoutID
      })
    }

  }
})
原文地址:https://www.cnblogs.com/ZJT7098/p/13994948.html