<div style='position:fixed;bottom:0;left:0; background:lightgray;width:100%;'>
About this SO question:
<a href='https://stackoverflow.com/a/17246304/1366033'>
setTimeout and array each
</a>
</div>
JavaScript
function ArrayPlusDelay1(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);
})
}
function ArrayPlusDelay2(array, delegate, delay) {
var i = 0
function loop() {
// each loop, call passed in function
delegate(array[i]);
// increment, and if we're still here, recurse again
if (i++ < array.length - 1)
setTimeout(loop, delay);
}
// seed first call
setTimeout(loop, delay);
}
function ArrayPlusDelay3(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
}
//ArrayPlusDelay1(['a','b','c'], function(obj) {console.log(obj)},1000)
//ArrayPlusDelay2(['d','e','f'], function(obj) {console.log(obj)},1000)
var int = ArrayPlusDelay3(['x','y','z'], function(obj) {console.log(obj)},1000)
// clear with clearInterval(int)
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.