防抖節流理解
阿新 • • 發佈:2021-08-06
先明白一個概念,防抖和節流的區別
防抖:瘋狂點選,在設定的這個時間段內只會傳送最後一次點選要求
節流:定時器設定的,在設定的時間間隔內只執行一次,迴圈進行
對於防抖的簡單函式編寫
<button id="debounce">點我防抖!</button> $('#debounce').on('click', function(){ let timer; return function () { clearTimeout(timer); timer = setTimeout(() => { console.log("防抖成功!"); }, 500); } });
防抖運用的方面之一,頁面滾動監聽,方法如下
function debounce(fn,delay) { let timer = null; return function () { let self = this, args = arguments; timer && clearTimeout(timer); timer = setTimeout(function () { fn.apply(self,args); },delay); } } window.onscroll= debounce(function () { let scrollTop = document.body.scrollTop || document.documentElement.scrollTop; console.log('滾動條位置:' + scrollTop); },200)
節流的簡單函式編寫
<button id="throttle">點我節流!</button> $('#throttle').on('click', throttle()); function throttle(fn) { let flag = true;return function () { if (!flag) { return; } flag = false; //此處設定的是一秒執行一次操作 setTimeout(() => { console.log("節流成功!"); flag = true; }, 1000); }; }
節流一遍用於對輸入框的請求,百度的搜尋框在我們輸入的時候就節流的操作
<input type="text" value="" id="input"> $('#input').on('keyup', throttle(function () { console.log($(this).val()) }, 1000)); function throttle(fn, delay) { let flag = true; return function () { let self = this, args = arguments; if (!flag) { return; } flag = false; setTimeout(() => { fn.apply(self, args); flag = true; }, delay); } }