AnswerBun.com

Is there a better way to implement nested setTimeouts()

Stack Overflow Asked by dashman on December 22, 2020

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.

One Answer

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

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

Correct answer by Rubydesic on December 22, 2020

Add your own answers!

Related Questions

Copy each cell in a range to multi-cell range

2  Asked on November 29, 2021 by preston-richardson

   

How to make dynamic custom textarea with jquery?

3  Asked on November 29, 2021 by david-noya

     

private static field Java

3  Asked on November 29, 2021

         

unordered_map excess calls to hash function

4  Asked on November 29, 2021 by amir-kirsh

   

cant load static file in django

1  Asked on November 29, 2021

       

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir