在前端开发中,我们经常需要处理一些延迟执行、防抖和节流的场景。今天介绍一个实用的delay
工具类,它提供了这些常用的延迟执行功能。
0、完整代码
/** * 延迟执行工具类 */ 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); } }; } }
1. 基础延迟执行
sleep方法
sleep方法提供了一个简单的延迟执行功能:
// 延迟2秒 await delay.sleep(2000); console.log('2秒后执行'); // 在async函数中使用 async function demo() { console.log('开始'); await delay.sleep(1000); console.log('1秒后'); }
execute方法
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);
2. 防抖(debounce)
防抖是指在短时间内多次触发同一个函数,只执行最后一次。典型场景包括:
- 搜索框输入
- 窗口调整
- 按钮点击
实现原理
每次触发时都会清除之前的定时器,重新设置一个新的定时器,确保只有在指定时间内没有新的触发时才执行函数。
使用示例
// 创建防抖函数 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);
3. 节流(throttle)
节流是指在一定时间间隔内只执行一次函数,无论这个函数被调用多少次。典型场景包括:
- 滚动事件处理
- 频繁点击
- 游戏中的射击
实现原理
通过一个标志位控制函数执行,在指定时间间隔内,该标志位为true时阻止函数执行,时间到后将标志位设为false允许下次执行。
使用示例
// 创建节流函数 const throttledscroll = delay.throttle(() => { console.log('页面滚动'); }, 200); // 在滚动事件中使用 window.addeventlistener('scroll', throttledscroll); // 游戏射击示例 const throttledshoot = delay.throttle(() => { console.log('发射子弹'); }, 1000); button.addeventlistener('click', throttledshoot);
防抖和节流的区别
防抖(debounce):
- 多次触发,只执行最后一次
- 适合输入框实时搜索等场景
- 重在清除之前的定时器
节流(throttle):
- 一定时间内只执行一次
- 适合滚动事件、频繁点击等场景
- 重在控制执行频率
总结
这个delay工具类提供了四个实用的方法:
- sleep: 基础延迟
- execute: 延迟执行函数
- debounce: 创建防抖函数
- throttle: 创建节流函数
通过合理使用这些方法,可以有效控制函数的执行时机,优化性能,提升用户体验。在实际开发中,要根据具体场景选择合适的方法使用。
到此这篇关于typescript实用的delay延迟执行工具类的文章就介绍到这了,更多相关typescript延迟执行内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论