DEV Community

WebDev
WebDev

Posted on

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

Top comments (0)