Skip to content

Instantly share code, notes, and snippets.

@hartum
Forked from 3n/gist:81451
Created March 19, 2009 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hartum/81779 to your computer and use it in GitHub Desktop.
Save hartum/81779 to your computer and use it in GitHub Desktop.
/*
Array.each_asynchronously
Description:
Works just like Array.each except runs each iteration on a specified delay.
This means that script execution will continue in between each iteration,
rather than halting until the full array has been processed.
Arguments:
- fn: (function) The function to execute on each item in the array. It is
passed three arguments: the item, the index and the array itself.
- delay: (number, optional) Duration of timer for each call to fn. Defaults
to 10ms.
- bind: (object, optional) The object to be used as 'this' in the fn.
Example:
['brawndo','has','electrolytes'].each_asynchronously(function(str,i,arr){
console.log(str);
}, 1000);
*/
Array.implement({
each_asynchronously: function(fn, delay, bind){
if (this.length == 0) return this;
var delay = delay || 10;
var items = this.concat();
var index = 0;
(function(){
fn.run([items.shift(), index, this], bind);
index += 1;
if (items.length > 0) setTimeout(arguments.callee.bind(this), delay);
}).delay(delay, this);
return this;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment