
节流是指在一定时间间隔内,确保某个函数不会被执行超过一次。即使在该时间间隔内多次触发函数,也只会执行一次。节流通常用于控制连续的事件触发频率,如滚动事件、窗口调整大小事件等。
throttle 函数下面是实现 throttle 函数的代码:
javascript 体验AI代码助手 代码解读复制代码function throttle(func, delay) {
let lastTime = 0; // 记录上一次执行的时间戳
return function (...args) {
const currentTime = new Date().getTime(); // 获取当前时间戳
if (currentTime - lastTime >= delay) {
func.apply(this, args); // 执行原始函数
lastTime = currentTime; // 更新上一次执行的时间戳
}
};
}
// 示例用法
const throttledFunc = throttle(() => {
console.log("Throttled function is executed!");
}, 1000);
// 触发频率高,但只在1秒内执行一次
setInterval(throttledFunc, 200);lastTime 用于记录上一次函数执行的时间戳。currentTime 获取当前的时间戳。delay,则执行函数 func。lastTime。防抖是指在连续的事件中,如果在指定时间内没有再次触发事件,则执行函数。如果在指定时间内再次触发事件,则重新计时。防抖通常用于控制输入框的输入事件处理等。
debounce 函数下面是实现 debounce 函数的代码:
javascript 体验AI代码助手 代码解读复制代码function debounce(func, delay) {
let timeoutId; // 记录定时器ID
return function (...args) {
clearTimeout(timeoutId); // 清除之前的定时器
timeoutId = setTimeout(() => {
func.apply(this, args); // 执行原始函数
}, delay);
};
}
// 示例用法
const debouncedFunc = debounce(() => {
console.log("Debounced function is executed!");
}, 1000);
// 触发频率高,但只在最后一次触发后的1秒内执行一次
for (let i = 0; i < 5; i++) {
setTimeout(debouncedFunc, 200 * i);
}timeoutId 用于记录当前的定时器ID。delay 后执行函数 func。本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。