在 JavaScript 中,防抖(debounce)和節(jié)流(throttle)是兩種常用的優(yōu)化高頻率觸發(fā)事件的技術。它們都可以用來控制函數的執(zhí)行頻率,從而提高性能。以下是它們的實現方法:
防抖的基本思想是:在事件被觸發(fā)后 n 秒內函數只能執(zhí)行一次,如果在這 n 秒內又被重新觸發(fā),則重新計時。
function debounce(func, wait) {
let timeout;
return function (...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args);
}, wait);
};
}
function debounce(func, wait) {
let timeout;
return function (...args) {
const context = this;
const later = function () {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
節(jié)流的基本思想是:預先設定一個執(zhí)行周期,周期內只執(zhí)行一次函數。
function throttle(func, limit) {
let inThrottle;
return function (...args) {
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => {
inThrottle = false;
}, limit);
}
};
}
Promise
和 async/await
function throttle(func, limit) {
let canRun = true;
return async function (...args) {
const context = this;
if (!canRun) return;
canRun = false;
await func.apply(context, args);
setTimeout(() => {
canRun = true;
}, limit);
};
}
以上就是 JavaScript 中防抖和節(jié)流的實現方法。在實際項目中,可以根據具體需求選擇合適的實現方式。