固定頻率下執行一些操做,好比聯想輸入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() } } })