Skip to content

Instantly share code, notes, and snippets.

@fitzgen
Created June 7, 2010 18:19
Show Gist options
  • Save fitzgen/428987 to your computer and use it in GitHub Desktop.
Save fitzgen/428987 to your computer and use it in GitHub Desktop.
// Based on Nicholas C Zakas' function in High Performance Javascript
function batchProcess(items, process, callback) {
// Create a copy of the original items array so that our side effects
// (calling .shift()) don't pollute anything outside of this scope.
var todo = items.slice(0);
setTimeout(function () {
var start = +new Date, result = true;
// Process the items in batch for 50ms, or until the iteration is
// canceled (by the process function returning false).
while
(result !== false
&& todo.length > 0
&& ((+new Date) - start < 50))
{
result = process(todo.shift());
}
// When the 50ms is up, let the UI thread update by defering the rest of
// the iteration in a setTimeout.
if (todo.length > 0 && result !== false) {
setTimeout(arguments.callee, 25);
} else {
callback(items);
}
}, 25);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment