关于javascript:节流和防抖

4次阅读

共计 667 个字符,预计需要花费 2 分钟才能阅读完成。

节流

固定频率下执行一些操作,比方联想输出

    function throttle(fn, delay) {
      let flag = true, // 加锁
          timer = null;
      return function (...args) {
        let context = this;
        if(!flag)return; // 如果还在固定频率内,不进行任何操作间接返回
        flag = false;
        clearTimeout(timer);
        timer = setTimeout(function () {fn.apply(context, args);
            flag = true;
        }, delay)
      }
    }

防抖

在限定工夫内续触发某个操作,仅执行最初一次操作,比方拖动弹窗须要一直计算并扭转地位

    function debounce(fn, delay) {
      let timer = null;
      return function(...args) {
        let context = this;
        if(timer)clearTimeout(timer); // 革除上一次的提早器,勾销事件触发
        timer = setTimeout(function() {fn.apply(context, args);
        },delay)
      }
    }

外围 setTimeout

节流——已有工作,间接返回
防抖——已有工作,从新定义

在 Vue 中的应用

new Vue({data() {
        return {throttle: null}
    },
    mounted() {this.throttle = throttle(()=>{// do something},1500)
    },
    methods: {exec() {this.throttle()
        }
    }
})
正文完
 0