I have written a small JavaScript class that makes use of setInterval
to create a delayed loop for iterating an array. I've used this technique in the past but never utilised a library to do so (and as a result it produced quite messy spaghetti code), and so I wrote up this:
var DelayedLoop = function() { };
DelayedLoop.forEach = function(collection, delay, callback, completedCallback) {
var index = 0;
var timerObject;
var executor = function() {
// Stop the delayed loop.
clearInterval(timerObject);
// Executes the callback, and gets the returned value to indicate what the next delay will be.
var newInterval = callback(collection[index++]);
// If they returned false, quit looping.
if(typeof(newInterval) == "boolean" && newInterval == false) {
return;
}
// If nothing / non-number is provided, re-use initial delay.
if(typeof(newInterval) != "number") {
newInterval = delay;
} else if(newInterval < 0) { // If a negative number is returned, quit looping.
return;
}
// If there are more elements to iterate, re-set delayed loop. Otherwise, call the "completed" callback.
if(index < collection.length) {
timerObject = setInterval(executor, newInterval);
} else {
completedCallback();
}
};
// Initial loop setup.
timerObject = setInterval(function() {
executor();
}, delay);
};
An example usage can be seen here:
$(document).ready(function() {
var myArray = [ "aaa", "bbb", "ccc" ];
DelayedLoop.forEach(myArray, 1000, function(arrayElement) {
console.log(arrayElement);
}, function() {
console.log("Finished all!");
});
});
How does it look? Are there any browser compatibility issues? Is there any potential flaw I'm not seeing?