zoukankan      html  css  js  c++  java
  • 小程序 节流搜索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
          })
        }
    
      }
    })
    
  • 相关阅读:
    并不对劲的loj3124:uoj477:p5405:[CTS2019]氪金手游
    并不对劲的loj6498. 「雅礼集训 2018 Day2」农民
    并不对劲的loj2251:p3688[ZJOI2017]树状数组
    并不对劲的loj2050:p3248:[HNOI2016]树
    并不对劲的BJOI2020
    并不对劲的loj3110:p5358:[SDOI2019]快速查询
    并不对劲的loj3111:p5359:[SDOI2019]染色
    (困难) CF 484E Sign on Fence,整体二分+线段树
    算法录 之 拓扑排序和欧拉路径。
    数据结构录 之 BST的高级应用。
  • 原文地址:https://www.cnblogs.com/ZJT7098/p/13994948.html
Copyright © 2011-2022 走看看