這篇文章主要介紹“JS函數節流和函數防抖實例介紹”,在日常操作中,相信很多人在JS函數節流和函數防抖實例介紹問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”JS函數節流和函數防抖實例介紹”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
在前端開發中有一部分的用戶行為會頻繁的觸發事件執行,而對于DOM操作、資源加載等耗費性能的處理,很可能導致界面卡頓,甚至瀏覽器的崩潰。函數節流(throttle)和函數防抖(debounce)就是為了解決類似需求應運而生的。
函數節流(throttle)
函數節流就是預定一個函數只有在大于等于執行周期時才執行,周期內調用不執行。好像水滴攢到一定重量才會落下一樣。
場景:
窗口調整(resize)
頁面滾動(scroll)
搶購瘋狂點擊(mousedown)
實現:
function throttle(method, delay){
var last = 0;
return function (){
var now = +new Date();
if(now - last > delay){
method.apply(this,arguments);
last = now;
}
}
}
document.getElementById('throttle').onclick = throttle(function(){console.log('click')},2000);underscore實現:
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
if (!options) options = {};
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
if (!timeout) context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
//計算剩余時間
var remaining = wait - (now - previous);
context = this;
args = arguments;
//剩余時間小于等于0或者剩余時間大于等待時間(本地時間變動出現)
if (remaining <= 0 || remaining > wait) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
previous = now;
result = func.apply(context, args);
if (!timeout) context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};函數防抖(debounce)
函數防抖就是在函數需要頻繁觸發情況時,只有足夠空閑的時間,才執行一次。好像公交司機會等人都上車后才出站一樣。
場景:
實時搜索(keyup)
拖拽(mousemove)
實現:
function debounce(method, delay){
var timer = null;
return function(){
var context = this,args = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
method.apply(context, args);
},delay);
}
}
document.getElementById('debounce').onclick = debounce(function(){console.log('click')},2000);underscore實現:
_.debounce = function(func, wait, immediate) {
var timeout, args, context, timestamp, result;
var later = function() {
var last = _.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
if (!timeout) context = args = null;
}
}
};
return function() {
context = this;
args = arguments;
timestamp = _.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
};函數節流(throttle)和函數防抖(debounce)都是通過延時邏輯操作來提升性能的方法,在前端優化中是常見且重要的解決方式??梢詮母拍詈蛯嶋H應用中理解兩者的區別,在需要的時候選擇合適的方法處理。
到此,關于“JS函數節流和函數防抖實例介紹”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。