小程序 節流搜索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
      })
    }

  }
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章