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:

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

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

async function delayExample() {
  //Say Hello
  console.log('Hello');
  // Say World after 2000 milliseconds
  await sleep(2000);
  console.log("World");
}

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

Angular Schulungen

In addition a more advanced implementation is the following function

function delay(ms: number, result?: T ) {
  return new Promise(resolve =>; setTimeout(() =>; resolve(result), ms));
}

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

async function delayExample() {
  // Logs: "Before sleep: and the current Date"
  console.log("Before sleep: " + new Date().toString());
  //Logs after 1000 milliseconds: "After Sleep: and the current Date"
  const result: string = await delay(1000, 'After sleep: ');
  console.log(result + new Date().toString());
}

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.

$ npm install delay

and used as follows

import * as delay from 'delay';
 
(async () =>; {
    bar();
 
    await delay(100);
 
    // Executed 100 milliseconds later
    baz();
})();

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

 

Avatar photo

theCodeCampus
Developer at thecodecampus </>

Our knowledge is not simply gained through reading - it is trained, tested and constantly being expanded. Because first and foremost, we are all developers at W11K. The know-how that we acquire here as developers, consultants and information architects flows immediately into our training courses and articles for 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.