节流

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

    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()        }    }})