February 11, 2020

Typescript delay with async/await

Sometimes it is necessary in JavaScript to delay/sleep a program for a certain time. Therefore we can generate this behavior ourselves using a small helper function, thanks to the asynchronous nature of javascript.

For example:

With this we can delay the program flow for a certain time in the following function

But it should be mentioned here that await can only be used inside an async function.

In addition a more advanced implementation is the following function

For instance, here we can optionally create a generic, which is returned after a successful function call.

For those who don’t want to implement such a help function every time themselves, there is the npm package delay which can be installed with the following command.

and used as follows

https://www.npmjs.com/package/delay

 

Related Posts

Admin Admin
Developer at thecodecampus </>


2 responses to “Typescript delay with async/await”

  1. Great content! Super high-quality! Keep it up! đŸ™‚

  2. horĂ¡cio says:

    Estou precisando mesmo de um script desse tipo!!! vou fazer uns testes em casa, se der certo , te dou um retorno em seguida!!! muito obrigado!!!!

Leave a Reply

Add code to your comment in Markdown syntax.
Like this:
`inline example`

```
code block
example
```

Your email address will not be published.