In TypeScript, implementing a sleep function is quite straightforward. The sleep function is typically used to pause code execution for a specified duration. This is commonly achieved in JavaScript or TypeScript by leveraging Promise along with the setTimeout function. Here, I'll demonstrate a simple example and explain how it works.
Implementing the Sleep Function in TypeScript
First, let's create a sleep function that accepts one parameter: the duration to pause (in milliseconds).
typescriptfunction sleep(ms: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, ms)); }
How to Use This Function
You can use the sleep function defined above as follows:
typescriptasync function demo() { console.log('Processing some tasks...'); await sleep(2000); // Wait for 2 seconds console.log('After 2 seconds, continue with other tasks'); } demo();
How It Works
-
Define the function: We define a function named
sleepthat takes a parametermsrepresenting the pause duration (in milliseconds). -
Create a Promise: The function returns a new
Promise. The Promise constructor accepts an executor function with two parameters:resolveandreject. Here, we only useresolve. -
Use
setTimeout: Inside the Promise, we callsetTimeout.setTimeoutis also asynchronous and executes a callback function after the specified time. In this case, the callback isresolve, meaning it resolves (completes) the Promise after the specified time. -
Wait for the Promise to resolve: The
demofunction is an asynchronous function, allowing us to use theawaitkeyword. Byawait sleep(2000);, we essentially pause execution here, wait for 2 seconds, and then continue with the subsequent code.
This approach, using Promise and setTimeout, is convenient for pausing function execution wherever needed, which is particularly useful when handling asynchronous logic or simulating long-running tasks.