Created
March 18, 2009 22:28
-
-
Save 3n/81451 to your computer and use it in GitHub Desktop.
Array.each_asynchronously: Works just like Array.each except runs each iteration on a specified delay.
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
/* | |
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