开发者

Running a long operation in 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 s开发者_开发问答o it can let its foreground/UI thread work again?

Something like this?

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


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.


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.


You could do something like:

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

This would execute your piece of code every 100 ms.


You can run the long job in the background.

Here is a very tiny library that allows you to do that: http://adambom.github.io/parallel.js/

It also uses all the computing power because it spawns across all CPU cores in the background.

Sample to put a long task in the background:

var slowSquare = function (n) { 
    var i = 0; 
    while (++i < n * n) {}
    return i; 
};
// Create a job
var p = new Parallel(100000);
// Spawn our slow function
p.spawn(slowSquare).then(yourCallback);

Sample for multicore:

var p = new Parallel([40, 41, 42]),
    log = function () { console.log(arguments); };

function fib(n) {
  return n < 2 ? 1 : fib(n - 1) + fib(n - 2);
};

p.map(fib).then(log); // returns [165580141, 267914296, 433494437]

It has a fallback to use Timeouts in case the browser doesn't supports workers.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜