Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested setTimeout alternative?

Tags:

javascript

I need to execute 3 functions in a 1 sec delay.

for simplicity those functions are :

console.log('1');
console.log('2');
console.log('3');

I could do this: ( very ugly)

 console.log('1')
 setTimeout(function () {
     setTimeout(function () {
         console.log('2')
         setTimeout(function () {
             console.log('3')

         }, 1000)
     }, 1000)

 }, 1000)

Or I could create an array of functions and use setInterval with global counter.

Is there any elegant way of doing this ?

(p.s. function no.2 is not dependent on function number 1... hence - every sec execute the next function.).

like image 566
Royi Namir Avatar asked Jul 10 '13 15:07

Royi Namir


People also ask

What can I use instead of setTimeout?

Instead of setTimeout, use run.

Can you nest setTimeout?

Nested setTimeout allows to set the delay between the executions more precisely than setInterval .

Is setTimeout deprecated?

We all know that passing a string to setTimeout (or setInterval ) is evil, because it is run in the global scope, has performance issues, is potentially insecure if you're injecting any parameters, etc. So doing this is definitely deprecated: setTimeout('doSomething(someVar)', 10000);

Is clearTimeout necessary?

You don't actually need to use clearTimeout , you only use it if you wish to cancel the timeout you already set before it happens. It's usually more practical to use clearInterval with setInterval because setInterval usually runs indefinitely.


2 Answers

setTimeout(function(){console.log('1')}, 1000);
setTimeout(function(){console.log('2')}, 2000);
setTimeout(function(){console.log('3')}, 3000);
like image 156
Salketer Avatar answered Oct 28 '22 13:10

Salketer


with async/await

const pause = _ => new Promise(resolve => setTimeout(resolve, _));

async function main() {
  await pause(1000);
  console.log('one');
  
  await pause(1000);
  console.log('two');
  
  await pause(1000);
  console.log('three');
}

main();

note this works in a loop too

const pause = _ => new Promise(resolve => setTimeout(resolve, _));

async function main() {
  for (let i = 0; i < 3; ++i) {
    await pause(1000);
    console.log(i + 1);
  }
}

main();
like image 22
gman Avatar answered Oct 28 '22 13:10

gman