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:
1 2 3 |
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
1 2 3 4 5 6 7 |
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.
In addition a more advanced implementation is the following function
1 2 3 |
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.
1 2 3 4 5 6 7 |
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.
1 |
$ npm install delay |
and used as follows
1 2 3 4 5 6 7 8 9 10 |
import * as delay from 'delay'; (async () =>; { bar(); await delay(100); // Executed 100 milliseconds later baz(); })(); |
https://www.npmjs.com/package/delay
Great content! Super high-quality! Keep it up! 🙂
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!!!!