tags:

views:

60

answers:

4

Hi,

Is there a good way of performing a long-running operation in javascript? For example, I have a function which may take 2 minutes to run. How do we break up a large operation like this? If I was using java or C, I would perform this task in a background thread. Is there a way to tell the browser to pause execution of the script so it can let its foreground/UI thread work again? Something like this?:

function bigJob() {
    for (i = 0; i < 1000000; i++) {
        someWork();
        sleep(1000);
    }
}

Thanks

A: 

If popups and such are enabled on the browser, you can open a new window outside of the viewing area and have it execute your script.

SOA Nerd
A: 

Possible ways:

  1. separate window
  2. chunks of work interleaved with timer
  3. HTML5 worker threads
  4. NPAPI plugin
  5. Extension

It all comes down to your requirements & constraints.

jldupont
+1  A: 

If you want it to sleep, you would run it in an interval:

var i = 0;    
var jobInterval = setInterval(bigJob, 1000);

function bigJob() {
      somework();

      i++;
      if(i>1000000) {
            clearInterval(jobInterval);
      }
}

You would have to track the number of iterations in the function, and kill the interval when you are done.

If someWork() is intensive, you will still hang the browser at each interval.

Jeff B
+1  A: 

You could do something like:

function bigJob() {
    setInterval(function() doPartOfTheJob, 100);
}

This would execute your piece of code every 100 ms.

aefxx