定时器setTimeout实现函数节流

问题描述

文字输入查询的keyup或oninput事件,实现实时查询功能。
在用户输入过程中,用户可能只想需要 '小' 字的查询结果,但是以上两个事件会触发'x'、'i'、'a'、'o'、'小',一共5次。
其中某个查询的匹配结果数据量大,返回速度慢,就会覆盖掉最终'小'字的查询结果。

解决方案

最开始我用函数节流或者是函数防抖的方法处理,在调试过程中报错。
原因是vue 2.0 移除了 debounce 属性,具体请查看从 Vue 1.x 迁移文档

最后手写了一个定时器,解决问题~~

<template>
  <div>
    <input type="text" @keyup="searchMedicine">
  </div>
</template>

<script>

  export default {
    data() {
      return {
        changeTime: new Date().getTime()
      }
    },
    methods: {
      searchMedicine() {
        this.changeTime = new Date().getTime()
         // 定时器    过滤密集输入
        setTimeout(() => {
          if (new Date().getTime() - this.changeTime >= 1000) {
            this.getDatas()
          }
        }, 1000)
      },
      getDatas() {
         // 这里写请求
         console.log('我是请求返回结果~~~~')
      }
    }
  }
</script>

总结

写的很粗糙,希望大家指点。

posted @ 2018-04-08 14:46  桃之夭夭~  阅读(1340)  评论(0编辑  收藏  举报