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 oneset 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) {
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() {
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
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
Then, if we ever want to clean it, just drop this in the console:
clearInterval(inter);
Similar questions:
- Using setimeout () with a loop
- Transition through an array with a time delay
- Scroll through an array, but with a time delay