函数节流、函数防抖的原理以及lodash的节流(throttle) 和 防抖(debounce)在vue+ts中的使用

安装依赖

npm i throttle-debounce-ts

 

区别:

  1. 函数节流在特定时间内触发一次任务,并且是规律的
  2. 函数防抖只有最后一次延时时间到达之后执行一次

应用场景:

  • throttle
  1. 鼠标不断点击触发,mousedown(单位时间内只触发一次)
  2. 监听滚动事件,比如是否滑到底部自动加载更多,用throttle来判断
  • debounce
  1. 百度搜索,用户在不断输入值时,用防抖来节约请求资源。
  2. window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次

lodash 的 节流(throttle) 和 防抖(debounce)
例:每隔300毫秒执行一次 onConfigDialogClick函数

<el-button type="primary" @click="saveDebounce">确 定</el-button>

//引用
import { throttle} from 'throttle-debounce-ts';

//使用
private saveDebounce = throttle(300, this.onConfigDialogClick);

// 点击确定按钮
  onConfigDialogClick() {
    const verifyResult = this.templateEditer.formVerifyResult();
    if (verifyResult !== '') {
      this.$message.warning(verifyResult);
      return;
    }
   //请求数据
    this.onRequestDataChanged();
  }

 

例:在停止点击300毫秒后,调用onConfigDialogClick方法

<el-button type="primary" @click="saveDebounce">确 定</el-button>

//引用
import { debounce } from 'throttle-debounce-ts';

//使用
private saveDebounce = debounce(300, this.onConfigDialogClick);

// 点击确定按钮
  onConfigDialogClick() {
    const verifyResult = this.templateEditer.formVerifyResult();
    if (verifyResult !== '') {
      this.$message.warning(verifyResult);
      return;
    }
   //请求数据
    this.onRequestDataChanged();
  }

 

posted @ 2020-12-31 16:15  潇潇mini  阅读(1884)  评论(0编辑  收藏  举报