Running CPU Intensive JavaScript Computations in a Web Browser
Written by on October 26th, 2007 in Ajax News.
Julien Lecomte has written up the pattern where you use setTimeout() to keep yielding control back to the main thread so that it can handle browser events.
Completion Callback
-
-
function doSomething (callbackFn [, additional arguments]) {
-
// Initialize a few things here…
-
(function () {
-
// Do a little bit of work here…
-
if (termination condition) {
-
// We are done
-
callbackFn();
-
} else {
-
// Process next chunk
-
setTimeout(arguments.callee, 0);
-
}
-
})();
-
}
-
Progress Callback
-
-
function doSomething (progressFn [, additional arguments]) {
-
// Initialize a few things here…
-
(function () {
-
// Do a little bit of work here…
-
if (continuation condition) {
-
// Inform the application of the progress
-
progressFn(value, total);
-
// Process next chunk
-
setTimeout(arguments.callee, 0);
-
}
-
})();
-
}
-
Of course, the Gears Workerpool does this the right way, giving you the ability to pass messages to another process to get the work done in a secure sandbox.
As a band-aid it could be nice to have an abstraction library that uses WorkerPool if Gears is installed, if not, try to use setTimeout (which is harder to do as you need to cut up the work differently).
Source: Ajaxian
Original Article: http://feeds.feedburner.com/~r/ajaxian/~3/175336022/running-cpu-intensive-javascript-computations-in-a-web-browser