Skip to content
DeveloperMemos

Creating a Blocking Delay in Typescript with Async Await

Typescript, async, await1 min read

Asynchronous programming is an important concept in modern software development, and Typescript offers powerful tools for working with asynchronous code. In this article, we will learn how to create a blocking delay using the async and await keywords in Typescript.

The async keyword is used to denote a function as asynchronous, which means that it will return a promise. This allows us to use the await keyword inside the function to wait for the result of an asynchronous operation.

For example, consider the following code:

1async function delay(milliseconds: number) {
2 return new Promise((resolve) => {
3 setTimeout(() => {
4 resolve();
5 }, milliseconds);
6 });
7}

Here, the delay function takes a number of milliseconds as an argument and returns a promise that will be resolved after the specified number of milliseconds has passed. This allows us to use the await keyword inside the delay function to pause execution until the delay has completed.

To use the delay function, we can call it inside an async function and await the result, like this:

1async function example() {
2 console.log("Starting delay...");
3 await delay(1000);
4 console.log("Delay complete!");
5}

In this example, the example function will print "Starting delay...", then wait for one second before printing "Delay complete!".

In summary, creating a blocking delay in Typescript with async and await is a simple and powerful way to work with asynchronous code. By using these keywords, we can pause execution until a promise is resolved, allowing us to write clean and readable asynchronous code in Typescript.