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

JAVASCRIPT:

  1.  
  2. function doSomething (callbackFn [, additional arguments]) {
  3.     // Initialize a few things here…
  4.     (function () {
  5.         // Do a little bit of work here…
  6.         if (termination condition) {
  7.             // We are done
  8.             callbackFn();
  9.         } else {
  10.             // Process next chunk
  11.             setTimeout(arguments.callee, 0);
  12.         }
  13.     })();
  14. }
  15.  

Progress Callback

JAVASCRIPT:

  1.  
  2. function doSomething (progressFn [, additional arguments]) {
  3.     // Initialize a few things here…
  4.     (function () {
  5.         // Do a little bit of work here…
  6.         if (continuation condition) {
  7.             // Inform the application of the progress
  8.             progressFn(value, total);
  9.             // Process next chunk
  10.             setTimeout(arguments.callee, 0);
  11.         }
  12.     })();
  13. }
  14.  

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

Leave a Reply

You must be logged in to post a comment.



Site Navigation