zoukankan      html  css  js  c++  java
  • 函数节流、函数防抖的原理以及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();
      }
  • 相关阅读:
    开始准备考研了
    ubuntu安装完vbox没有无缝模式
    Terminator快捷键
    ubuntu启动慢显示waiting for network configuration
    terminal快捷键
    openstack根据软件选择实例resume
    输出数组的全排列
    给非同步的集合加锁原理。
    集合框架—ArrayList的用法
    集合框架 Map的小例子
  • 原文地址:https://www.cnblogs.com/xiaoxiaomini/p/14217482.html
Copyright © 2011-2022 走看看