Created
June 7, 2010 18:19
-
-
Save fitzgen/428987 to your computer and use it in GitHub Desktop.
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
// 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