一、函數(shù)節(jié)流
某函數(shù)在指定時(shí)間間隔內(nèi)執(zhí)行,如:每1秒執(zhí)行一次
1、第一次就執(zhí)行
// 對(duì)函數(shù)進(jìn)行 節(jié)流
function throttle (fn, delay = 1000) {
let flag = true;
return (...args) => {
if (flag) {
flag = false;
fn(...args);
setTimeout(() => {
flag = true;
}, delay);
}
};
}
// 需要被節(jié)流的 函數(shù)
function scrollHandler (arg) {
console.log(`${arg}--被執(zhí)行了`);
}
// 被節(jié)流的函數(shù) -- 節(jié)流限制: 每 1000 毫秒執(zhí)行一次
const throttleFunc = throttle(scrollHandler, 1000);
let i = 0;
// 模擬 頁(yè)面滾動(dòng)事件
const interval = setInterval(() => {
console.log(`我是:${i}`);
throttleFunc(i++);
}, 10);
2、首次不執(zhí)行,需等待delay時(shí)間后才能執(zhí)行第一次
function throttle(fn, delay = 1000) {
let prevTime = Date.now();
return function () {
let curTime = Date.now();
if (curTime - prevTime > delay) {
fn.apply(this, arguments);
prevTime = curTime;
}
};
}
// 需要被節(jié)流的 函數(shù)
function scrollHandler (arg) {
console.log(`${arg}--被執(zhí)行了`);
}
// 被節(jié)流的函數(shù) -- 節(jié)流限制: 每 1000 毫秒執(zhí)行一次
const throttleFunc = throttle(scrollHandler, 1000);
let i = 0;
// 模擬 頁(yè)面滾動(dòng)事件
const interval = setInterval(() => {
console.log(`${i} --- 進(jìn)來(lái)了,但是不知道有沒(méi)有執(zhí)行`);
throttleFunc(i++);
}, 10);
二、函數(shù)防抖
當(dāng)持續(xù)觸發(fā)事件時(shí),只有在規(guī)定時(shí)間段內(nèi)沒(méi)有再觸發(fā)事件,事件處理函數(shù)才會(huì)執(zhí)行一次,如果設(shè)定的時(shí)間到來(lái)之前,又一次觸發(fā)了事件,就重新開(kāi)始延時(shí)。
就像游戲里放技能時(shí)需要讀條一樣,讀條結(jié)束才能放出技能,但是在讀條結(jié)束前,你又按了一次技能,那么只能重新讀條。
function debounce(func, wait) {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}
// 使用
window.onscroll = debounce(function() {
console.log('debounce');
}, 1000);