固定频率下执行一些操做,好比联想输入javascript
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) } }
在限定时间内续触发某个操做,仅执行最后一次操做,好比拖动弹窗须要不断计算并改变位置java
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) } }
节流——已有任务,直接返回
防抖——已有任务,从新定义app
new Vue({ data() { return { throttle: null } }, mounted() { this.throttle = throttle(()=>{ // do something },1500) }, methods: { exec() { this.throttle() } } })