場景
在我們日常開發中,有許多場景都會導致同一事件被頻繁觸發,嚴重的會導致瀏覽器崩潰。
- Window對象的resize、scroll事件
- 拖拽時元素時的mousemove事件
- 按鍵的mousedown、keydown、keyup事件
- …
解決
那麼,爲了避免性能過差或者瀏覽器崩潰,就有了防抖
、節流
一說
debounce(防抖)
當調用函數n毫秒
後,纔會執行該動作,若在這n毫秒內又調用此動作則將重新計算執行時間。這種比較適合window
的resize
事件,實際需求大多爲停止改變大小n毫秒
後執行後續處理。
function debounce(fn, wait) {
var timer = null;
return function () {
var context = this;
var args = arguments;
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function () {
fn.apply(context, args)
}, wait)
}
}
throttle(節流)
當連續調用函數時,再計時器的週期內只會執行函數一次。
function throttle(fn, wait) {
var timer;
return function () {
var context = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function () {
timer = null;
fn.apply(context, args);
}, wait);
}
};
};
使用
配合jquery
// 防抖
$(window).resize(debounce(function () {
console.log('window, resize');
}, 300))
// 節流
$('input').keyup(throttle(function(){
console.log($(this).val());
}, 300))