Created
December 1, 2011 04:58
-
-
Save nanha/1413792 to your computer and use it in GitHub Desktop.
Async foreach
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.prototype.asyncEach = function(iterator) { | |
| var list = this, | |
| n = list.length, | |
| i = -1, | |
| calls = 0, | |
| looping = false; | |
| var iterate = function() { | |
| calls -= 1; | |
| i += 1; | |
| if (i === n) return; | |
| iterator(list[i], resume); | |
| }; | |
| var loop = function() { | |
| if (looping) return; | |
| looping = true; | |
| while (calls > 0) iterate(); | |
| looping = false; | |
| }; | |
| var resume = function() { | |
| calls += 1; | |
| if (typeof setTimeout === 'undefined') loop(); | |
| else setTimeout(iterate, 1); | |
| }; | |
| resume(); | |
| }; | |
| 사용방법 | |
| list.asyncEach(function(item, resume) { | |
| // handle item | |
| resume(); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment