以下內(nèi)容是引用或者借鑒別人的蜗巧,自己只是做個筆記幕屹,方便學(xué)習(xí)级遭。理解錯誤的地方挫鸽,歡迎評論丢郊。如有侵權(quán)蚂夕,私聊我刪除婿牍,未經(jīng)允許等脂,不準(zhǔn)作為商業(yè)用途
防抖:在n秒內(nèi)撑蚌,連續(xù)觸發(fā)同一事件争涌,前面的都不執(zhí)行,只執(zhí)行最后一次方法
- 思路:在n秒內(nèi)再次被觸發(fā)伟骨,則清除定時器燃异,讓它重新開始計時
/**
* @desc 函數(shù)防抖
* @param func 函數(shù)
* @param wait 延遲執(zhí)行毫秒數(shù)
* @param immediate true 表立即執(zhí)行回俐,false 表非立即執(zhí)行
*/
function debounce(func,wait=1000,immediate=false) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
var callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait)
if (callNow) func.apply(context, args)
}
else {
timeout = setTimeout(function(){
func.apply(context, args)
}, wait);
}
}
}
節(jié)流:在n秒內(nèi)仅颇,連續(xù)觸發(fā)同一事件忘瓦,只執(zhí)行第一次方法,最后都不執(zhí)行
- 思路:在n秒內(nèi)第一次觸發(fā)時枚抵,添加鎖機制汽摹,等到執(zhí)行了函數(shù)再釋放
function throttle(func, wait=1000) {
let timeout;
return function() {
let context = this;
let args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}