How to use setTimeout with async/await in Javascript

Many times there are cases when we have to use delay some functionality in javascript and the function we use for this is setTimeout(). in regular functions it works vey well and does its job, however, it becomes tricky to delay an async function using setTimeout like this:

async function someFunction() {
 setTimeout(() => {
      await someOtherFunction();
    }, 5000);
}

This will not work as you will get an error like:

Parsing error: Can not use keyword 'await' outside an async function(undefined)

To fix this issue, we have to play a bit of trick and refactor our code like:

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function someFunction() {
 await delay(5000);
 await someOtherFunction();
}

Leave a Reply

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