Skip to content

Instantly share code, notes, and snippets.

@icodejs
Created April 8, 2012 08:46
Show Gist options
  • Save icodejs/2336090 to your computer and use it in GitHub Desktop.
Save icodejs/2336090 to your computer and use it in GitHub Desktop.
Timed Process Array
// timedProcessArray
// Since each new Date object is initialized with the current system time, you can time
// code by creating new Date objects periodically and comparing their values. The plus
// operator (+) converts the Date object into a numeric representation so that any further
// arithmetic doesn’t involve conversions. This same basic technique can be used to op-
// timize the previous timer patterns.
function timedProcessArray(items, process, callback){
var todo = items.concat(); //create a clone of the original
setTimeout(function(){
var start = +new Date();
do {
process(todo.shift());
} while (todo.length > 0 && (+new Date() - start < 50));
if (todo.length > 0){
setTimeout(arguments.callee, 25);
} else {
callback(items);
}
}, 25);
}
// The addition of a do-while loop in this function enables checking the time after each
// item is processed. The array will always contain at least one item when the timer func-
// tion executes, so a post-test loop makes more sense than a pretest one. When run in
// Firefox 3, this function processes an array of 1,000 items, where process() is an empty
// function, in 38–43 milliseconds; the original processArray() function processes the
// same array in over 25,000 milliseconds. This is the power of timing tasks before break-
// ing them up into smaller chunks.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment