在前端开发中,我们经常需要处理一些延迟执行、防抖和节流的场景。今天介绍一个实用的Delay
工具类,它提供了这些常用的延迟执行功能。
/**
* 延迟执行工具类
*/
export class Delay {
/**
* 延迟指定时间
* @param ms 延迟的毫秒数
* @returns Promise对象
*/
static sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* 延迟执行函数
* @param fn 要执行的函数
* @param ms 延迟的毫秒数
* @returns Promise对象,包含函数执行结果
*/
static async execute<T>(fn: () => T | Promise<T>, ms: number): Promise<T> {
await this.sleep(ms);
return await fn();
}
/**
* 创建防抖函数
* @param fn 要执行的函数
* @param ms 延迟时间
* @returns 防抖后的函数
*/
static debounce<T extends (...args: any[]) => any>(fn: T, ms: number): (...args: Parameters<T>) => void {
let timeoutId: NodeJS.Timeout;
return function (...args: Parameters<T>) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), ms);
};
}
/**
* 创建节流函数
* @param fn 要执行的函数
* @param ms 间隔时间
* @returns 节流后的函数
*/
static throttle<T extends (...args: any[]) => any>(fn: T, ms: number): (...args: Parameters<T>) => void {
let isThrottled = false;
return function (...args: Parameters<T>) {
if (!isThrottled) {
fn.apply(this, args);
isThrottled = true;
setTimeout(() => isThrottled = false, ms);
}
};
}
}
sleep
方法提供了一个简单的延迟执行功能:
// 延迟2秒
await Delay.sleep(2000);
console.log('2秒后执行');
// 在async函数中使用
async function demo() {
console.log('开始');
await Delay.sleep(1000);
console.log('1秒后');
}
execute
方法可以延迟执行一个函数:
// 延迟3秒执行函数
const result = await Delay.execute(() => {
return '延迟执行的结果';
}, 3000);
// 异步函数示例
await Delay.execute(async () => {
const response = await fetch('https://api.example.com/data');
return response.json();
}, 1000);
防抖是指在短时间内多次触发同一个函数,只执行最后一次。典型场景包括:
每次触发时都会清除之前的定时器,重新设置一个新的定时器,确保只有在指定时间内没有新的触发时才执行函数。
// 创建防抖函数
const debouncedSearch = Delay.debounce((searchTerm: string) => {
console.log('搜索:', searchTerm);
}, 500);
// 在输入框onChange事件中使用
<input onChange={(e) => debouncedSearch(e.target.value)} />
// 窗口调整示例
const debouncedResize = Delay.debounce(() => {
console.log('窗口大小改变');
}, 200);
window.addEventListener('resize', debouncedResize);
节流是指在一定时间间隔内只执行一次函数,无论这个函数被调用多少次。典型场景包括:
通过一个标志位控制函数执行,在指定时间间隔内,该标志位为true时阻止函数执行,时间到后将标志位设为false允许下次执行。
// 创建节流函数
const throttledScroll = Delay.throttle(() => {
console.log('页面滚动');
}, 200);
// 在滚动事件中使用
window.addEventListener('scroll', throttledScroll);
// 游戏射击示例
const throttledShoot = Delay.throttle(() => {
console.log('发射子弹');
}, 1000);
button.addEventListener('click', throttledShoot);
这个Delay
工具类提供了四个实用的方法:
sleep
: 基础延迟execute
: 延迟执行函数debounce
: 创建防抖函数throttle
: 创建节流函数通过合理使用这些方法,可以有效控制函数的执行时机,优化性能,提升用户体验。在实际开发中,要根据具体场景选择合适的方法使用。