Categories
TypeScript Answers

How to implement sleep function in TypeScript?

Spread the love

Sometimes, we want to implement sleep function in TypeScript.

In this article, we’ll look at how to implement sleep function in TypeScript.

How to implement sleep function in TypeScript?

To implement sleep function in TypeScript, we can create a function that returns a promise that calls setTimeout.

For instance, we write

const delay = (ms: number) => {
  return new Promise((resolve) => setTimeout(resolve, ms));
};

to create the delay function that returns a promise that calls resolve after ms milliseconds is up.

We create the promise using the Promise constructor with a callback that calls setTimeout as the argument.

Then we can use it by writing

(async () => {
  console.log("before delay");
  await delay(1000);
  console.log("after delay");
})();

We use await to log 'after delay' only after the delay function’s returned promise is resolved.

Conclusion

To implement sleep function in TypeScript, we can create a function that returns a promise that calls setTimeout.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *