How to add 5 seconds delay without locking up UI using ES6 async/await

webdev122

WebDev

Posted on July 24, 2022

How to add 5 seconds delay without locking up UI using ES6 async/await

You will need to promisify sleep function manually.

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}
async function sleep(fn, ...args) {
    await timeout(3000);
    return fn(...args);
}
Enter fullscreen mode Exit fullscreen mode

Btw, to slow down your loop you probably don't want to use a sleep function that takes a callback and defers it like this:

while (goOn) {
  // other code
  var [parents] = await Promise.all([
      fn(...args).then(
        //code here
      ),
      timeout(5000)
  ]);
  // other code
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
webdev122
WebDev

Posted on July 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related