Settimeout and array each

I am confused about using setTimeout and each iterator. How can I rewrite the following so that the console displays each name after a delay of 5 seconds? Currently, the code below prints all the names immediately after 5 seconds. I would like to:

1) wait 5 seconds, then print kevin
2) wait 5 seconds, then print the microphone
3) wait 5 seconds, then print sally

var ary = ['kevin', 'mike', 'sally']; _(ary).each(function(person){ setTimeout(function(){ console.log(person); }, 5000); }); 
+7
source share
5 answers

You can create a variable called offset that will make the timer wait another 5 seconds for each person in the array, for example:

 var ary = ['kevin', 'mike', 'sally']; var offset = 0; _(ary).each(function(person){ setTimeout(function(){ console.log(person); }, 5000 + offset); offset += 5000; }); 
+7
source

You could do

 var ary = ['kevin', 'mike', 'sally']; _(ary).each(function(person, index){ setTimeout(function(){ console.log(person); }, index * 5000); }); 

Without increasing the timeout value, you must initialize all setTimeouts with the same value (which is why you see what you see).

+6
source

You have three main options:

  • For loop + setTimeout
    ... initialize everyone immediately, but the step-by-step start time is based on the position of the index so that they do not all go at the same time.
  • set Timeout + conditional recursion
    ... check every n seconds - and I will tell you if you need to do another one
  • set Interval + conditional clearInterval
    ... keep working every n seconds - until I tell you to stop

Here, each of them is concretized with a working example:

1. For the loop + setTimeout

A few notes on this. It is like starting a relay race and giving instructions before each runner to start at exactly 5:00 and 5:02 and 5:04, regardless of whether the person behind them had finished a long time ago or hasnโ€™t arrived yet.

In addition, you cannot use the usual for i=0 loop , because the for statement does not define a new scope of functions. Thus, the values โ€‹โ€‹of the objects set in each for loop will be applied in all iterations. By the time setTimeout is called, it will use only the most recent value. Therefore, we need to close to save the value in each cycle. I used Array.prototype.forEach() , but if you want to use forEach implementations in jQuery or Underscore, this will work too.

 function ArrayPlusDelay(array, delegate, delay) { // initialize all calls right away array.forEach(function (el, i) { setTimeout(function() { // each loop, call passed in function delegate( array[i]); // stagger the timeout for each loop by the index }, i * delay); }) } // call like this ArrayPlusDelay(['a','b','c'], function(obj) {console.log(obj)},1000) 

2. setTimeout + conditional recursion

For the bottom two options, we create our own loops, so we will have to track the index ourselves, initializing a zero value and increasing it.

To do this, we a) call setTimeout , which will be executed once, b) evaluate the array at the index position, c) check if there are more elements in the array, and if so, start with (a).

 function ArrayPlusDelay(array, delegate, delay) { var i = 0 function loop() { // each loop, call passed in function delegate(array[i]); // increment, and if we're still here, call again if (i++ < array.length - 1) setTimeout(loop, delay); //recursive } // seed first call setTimeout(loop, delay); } // call like this ArrayPlusDelay(['d','e','f'], function(obj) {console.log(obj)},1000) 

3. setInterval + conditional clearInterval

NOTE The setInterval function will run forever after the call. This return value, when initially set, will provide a reference to the interval, so it is often combined with the clearInterval function to optionally disable it down the road

 function ArrayPlusDelay(array, delegate, delay) { var i = 0 // seed first call and store interval (to clear later) var interval = setInterval(function() { // each loop, call passed in function delegate(array[i]); // increment, and if we're past array, clear interval if (i++ >= array.length - 1) clearInterval(interval); }, delay) } ArrayPlusDelay(['x','y','z'], function(obj) {console.log(obj)},1000) 

3 * Secret Fourth Option (Best)

Options 1 and 2 are risky, because as soon as you send this train, there is no way to call it on the road (except for closing the browser). If you have a large array or a heavy load from your delegate, it might be nice to provide some resources if you need it. By saving the link from setInterval , we will have constant access to the iteration function. We just need to return the object of the interval above and save it when calling our function plus plus delays.

 function ArrayPlusDelay(array, delegate, delay) { var i = 0 // seed first call and store interval (to clear later) var interval = setInterval(function() { // each loop, call passed in function delegate(array[i]); // increment, and if we're past array, clear interval if (i++ >= array.length - 1) clearInterval(interval); }, delay) return interval } var inter = ArrayPlusDelay(['x','y','z'], function(obj) {console.log(obj)},1000) 

Then, if we ever want to clean it, just drop this in the console:

 clearInterval(inter); 

All 3 demos in jsFiddle

Similar questions:

  • Using setimeout () with a loop
  • Transition through an array with a time delay
  • Scroll through an array, but with a time delay
+3
source

each usually better for things that happen immediately.

Instead, if you don't mind changing the array, you can use it as a queue:

 var ary = ['kevin', 'mike', 'sally']; setTimeout(function loop() { console.log(ary.shift()); if (ary.length) setTimeout(loop, 5000); }, 5000); 

He continues to call loop 5 seconds in the future until there is nothing left in the queue.

+1
source

You can simply use setInterval () with a simple counter one at a time.

 var ary = ['kevin', 'mike', 'sally']; var i=0; setInterval(function(){ console.log(ary[i]); i++; }, 5000); 

But note that this will start throwing errors after I become more than two. You need to have some kind of check and make sure you clear the interval.

-one
source

All Articles