Last active
August 29, 2015 14:13
-
-
Save andy-williams/f5406b8a0435372b29b3 to your computer and use it in GitHub Desktop.
Iterative through an array with a delay based on // http://stackoverflow.com/questions/12926531/javascript-delay-between-function-calls-for-each-index-in-an-array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function iterateArrayWithDelay(argsArr, delay, fn) { | |
var index = 0; | |
function next() { | |
// protect against empty array | |
if (!argsArr.length) { | |
return; | |
} | |
// call the callback | |
fn(index, argsArr[index]); | |
++index; | |
if(index != argsArr.length) { | |
setTimeout(next, delay); | |
} | |
} | |
// start the iteration | |
next(); | |
} | |
// test | |
function iterateArrayWithDelayTest() { | |
var args = [5,4,3,2,1]; | |
iterateArrayWithDelay(args, 1000, function(i, num) { | |
console.log("index: " + i + ", value: " + num); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment