In front-end development, we often need to deal with some scenarios of delayed execution, anti-shake and throttling. Today I will introduce a practical oneDelay
Tool class, which provides these commonly used delayed execution functions.
0. Complete code
/** * Delayed execution tool class */ export class Delay { /** * Delay specified time * @param ms The number of milliseconds of delay * @returns Promise object */ static sleep(ms: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, ms)); } /** * Delayed execution of functions * @param fn Function to execute * @param ms The number of milliseconds of delay * @returns Promise object, containing the function execution result */ static async execute<T>(fn: () => T | Promise<T>, ms: number): Promise<T> { await (ms); return await fn(); } /** * Create anti-shake function * @param fn Function to execute * @param ms Delay time * @returns Function after anti-shake */ static debounce<T extends (...args: any[]) => any>(fn: T, ms: number): (...args: Parameters<T>) => void { let timeoutId: ; return function (...args: Parameters<T>) { clearTimeout(timeoutId); timeoutId = setTimeout(() => (this, args), ms); }; } /** * Create throttling functions * @param fn Function to execute * @param ms interval time * @returns throttling function */ 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) { (this, args); isThrottled = true; setTimeout(() => isThrottled = false, ms); } }; } }
1. Basic delayed execution
Sleep method
The sleep method provides a simple delay execution function:
// Delay 2 secondsawait (2000); ('Execute in 2 seconds'); // Use in async functionasync function demo() { ('start'); await (1000); ('After 1 second'); }
execute method
The execute method can delay execution of a function:
// Delay 3 seconds to execute the functionconst result = await (() => { return 'The result of delayed execution'; }, 3000); // Asynchronous function exampleawait (async () => { const response = await fetch('/data'); return (); }, 1000);
2. Anti-shake (Debounce)
Anti-shake means triggering the same function multiple times in a short period of time and only executing it last time. Typical scenarios include:
- Search box input
- Window adjustment
- Button click
Implementation principle
Each time the trigger is triggered, a new timer is reset, ensuring that the function is executed only if there is no new trigger within the specified time.
Example of usage
// Create anti-shake functionconst debouncedSearch = ((searchTerm: string) => { ('search:', searchTerm); }, 500); // Use in the onChange event in the input box<input onChange={(e) => debouncedSearch()} /> // Window adjustment exampleconst debouncedResize = (() => { ('Window size changes'); }, 200); ('resize', debouncedResize);
3. Throttle
Throttle means that a function is executed only once within a certain time interval, no matter how many times the function is called. Typical scenarios include:
- Scrolling event processing
- Frequently click
- Shooting in the game
Implementation principle
Execution is controlled by a flag bit. During the specified time interval, the function is blocked when the flag bit is true. After the time is up, the flag bit is set to false to allow the next execution.
Example of usage
// Create throttling functionconst throttledScroll = (() => { ('Page scrolling'); }, 200); // Use in scrolling events('scroll', throttledScroll); // Game shooting exampleconst throttledShoot = (() => { ('Shot bullets'); }, 1000); ('click', throttledShoot);
The difference between anti-shake and throttling
Anti-shake (Debounce):
- Triggered multiple times, only the last time
- Suitable for real-time search of input boxes and other scenarios
- Recently clear the timer before clearing
Throttle:
- Only execute once within a certain period of time
- Suitable for scrolling events, frequent clicks and other scenarios
- Focus on controlling the execution frequency
Summarize
This Delay tool class provides four practical methods:
- sleep: basic delay
- execute: Delayed execution of functions
- debounce: Create anti-shake function
- throttle: Create throttling function
By using these methods reasonably, the execution timing of functions can be effectively controlled, performance can be optimized, and user experience can be improved. In actual development, you should choose the appropriate method to use according to the specific scenario.
This is the article about TypeScript's practical Delay Delay Execution Tool. For more related content on TypeScript, please search for my previous articles or continue browsing the related articles below. I hope you will support me in the future!