如何通过原生js实现一个节流函数和防抖函数?

110 阅读1分钟

节流函数(Throttle)

节流函数限制一个函数在一定时间间隔内只能执行一次。以下是一个原生JavaScript的节流函数的实现示例:

function throttle(func, delay) {
let lastTime = 0;
return function() {
 const now = Date.now();
 if (now - lastTime >= delay) {
   func.apply(this, arguments);
   lastTime = now;
 }
};
}

使用方法:

js
function handleThrottle() {
console.log("Throttle function is called");
}

const throttledFunc = throttle(handleThrottle, 1000);

// 在需要的地方调用 throttledFunc
*2. 防抖函数(Debounce)**:

防抖函数会等待一段时间后,执行一次函数。如果在等待时间内再次触发函数,等待时间会重新计时。以下是一个原生JavaScript的防抖函数的实现示例:
function debounce(func, delay) {
let timer;
return function() {
 clearTimeout(timer);
 timer = setTimeout(() => {
   func.apply(this, arguments);
 }, delay);
};
}
使用方法:
function handleDebounce() {
console.log("Debounce function is called");
}

const debouncedFunc = debounce(handleDebounce, 1000);

// 在需要的地方调用 debouncedFunc
这两个函数可以根据需要在事件处理程序、滚动事件、输入框输入等情况下使用,以减少频繁触发函数的次数,提高性能。根据实际需求,你可以调整节流和防抖的时间间隔来满足特定的场景要求。