Last active
November 25, 2021 11:06
-
-
Save neilk/5380684 to your computer and use it in GitHub Desktop.
Works a little bit like `Array.prototype.forEach()`, but uses `process.nextTick` to allow other processes to execute. NOTE. This isn't meant to be practical; if you use this in production code you're probably doing it wrong.
This file contains 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
/** | |
* Allow other processes to execute while iterating over | |
* an array. Useful for large arrays, or long-running processing | |
* | |
* @param {Function} fn iterator fed each element of the array. | |
* @param {Function} next executed when done | |
*/ | |
Array.prototype.nonBlockingForEach = function(fn, next) { | |
var arr = this; | |
var i = 0; | |
var len = arr.length; | |
function iter() { | |
if (i < len) { | |
fn(arr[i]); | |
i++; | |
process.nextTick(iter); | |
} else { | |
next(); | |
} | |
} | |
iter(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use setImmediate instead of process.nextTick