dashman
dashman

Reputation: 3028

Is there a better way to implement nested setTimeouts()

I've got a code segment that requires nested set-timeouts. Do something...wait for a while and then do something and wait for a while.

setTimeout( () =>
{
   // do stuff..
   //
   setTimeout () =>
   {
      // some more
   }, 2000 );

}, 1000 );

Is there a better way to implement above in modern Javascript - maybe using Promise.

Upvotes: 0

Views: 139

Answers (1)

Rubydesic
Rubydesic

Reputation: 3476

function sleep(time) {
    return new Promise(res => setTimeout(res, time))
}

async function doThings() {
    await sleep(1000)
    // do stuff
    await sleep(2000)
    // some more
}

Upvotes: 3

Related Questions