Skip to content

Instantly share code, notes, and snippets.

@radiumrasheed
Forked from seanmonstar/Array.batch.js
Created February 3, 2022 18:33
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 radiumrasheed/96ba8285a72ad0a206a43f8fbfc6aeb2 to your computer and use it in GitHub Desktop.
Save radiumrasheed/96ba8285a72ad0a206a43f8fbfc6aeb2 to your computer and use it in GitHub Desktop.
Similar to Array.each, but loops in batches, use setTimeout to allow the Browser thread to do other things, like respond to UI events and changes. Useful for really big arrays, or really intensive functions.
Array.implement('batch', function(callback, loopsPerBatch, delay, bind) {
if(!loopsPerBatch) loopsPerBatch = 10;
if(!delay) delay = 50;
if(callback) {
var loops = 0,
index = 0,
that = this;
function doLoops() {
loops = 0;
for (var length = that.length; (index < length) && loops < loopsPerBatch; index++) {
loops++;
callback.call(bind, that[index], index, that);
}
if(index < length) {
doLoops.delay(delay);
}
}
doLoops();
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment