Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a long operation in javascript?

Tags:

javascript

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);
    }
}
like image 271
user246114 Avatar asked Feb 04 '10 00:02

user246114


2 Answers

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.

like image 88
Jeff B Avatar answered Oct 02 '22 21:10

Jeff B


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.

like image 45
jldupont Avatar answered Oct 02 '22 19:10

jldupont