实现节流函数
节流函数的作用是,在一定时间间隔内只执行一次函数调用。
function throttle(func, delay) {
let timerId;
let lastExecTime = 0;
return function (...args) {
const currentTime = Date.now();
const elapsedTime = currentTime - lastExecTime;
if (!timerId || elapsedTime >= delay) {
func.apply(this, args);
lastExecTime = Date.now();
} else {
clearTimeout(timerId);
timerId = setTimeout(() => {
func.apply(this, args);
lastExecTime = Date.now();
}, delay - elapsedTime);
}
};
}
实现防抖函数
防抖函数的作用是,在一定的时间间隔内,如果没有再次触发该函数,那么才会去执行函数体内的代码(例如发送网络请求)。
function debounce(func, delay) {
let timerId;
return function (...args) {
clearTimeout(timerId);
timerId = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}