Open In App

How to implement sleep function in TypeScript?

In this article, we will learn How to implement sleep function in TypeScript. Sleep allows the calling thread/program to pause its execution for a specified number of seconds. In TypeScript, you can’t use the traditional synchronous sleep function as you would in some other languages like Python or JavaScript. This is because JavaScript, and by extension TypeScript, is single-threaded, and blocking the main thread would freeze your entire application. However, you can implement a sleep-like function using asynchronous features, such as async/await and Promise.

Syntax:

async function sleep(ms: number): Promise<void> {
return new Promise(
(resolve)
=> setTimeout(resolve, ms));
}

Parameters:

Example 1: This code defines an async function named sleep, which returns a promise to sleep for the given number of milliseconds. The run function demonstrates how to use the sleep function to introduce delays within an async program.






async function sleep(ms: number): Promise<void> {
    return new Promise(
        (resolve) => setTimeout(resolve, ms));
}
 
async function run() {
    console.log("Start of the program");
     
    // Sleep for 2 seconds
    await sleep(2000);
    console.log("After 2 seconds");
     
    // Sleep for an additional 3 seconds
    await sleep(3000);
    console.log("After another 3 seconds");
}
 
run();

Output:



Example 2: This code defines a sleep function that returns a promise to sleep for a given number of milliseconds. The delayAndLog function logs a message, sleeps for a specified duration, and then logs another message when it wakes up.




function sleep(ms: number): Promise<void> {
    return new Promise(
        (resolve) =>
            setTimeout(resolve, ms));
}
 
async function delayAndLog(
    message: string, delayMs: number) {
    console.log(
        `Sleeping for ${delayMs}
         milliseconds...`);
    await sleep(delayMs);
    console.log(
        `Woke up after sleeping for
         ${delayMs} milliseconds. Message: ${message}`);
}
 
delayAndLog("GeeksforGeeks!", 2000);

Output:


Article Tags :