Running a long operation in javascript?

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.


You could do something like:

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

This would execute your piece of code every 100 ms.


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.

Tags:

Javascript