Running a long running operation in javascript?

Is there a good way to do long term work in javascript? For example, I have a function that can take 2 minutes. How can we beat such a big operation? If I were using java or C, I would do this task in the background thread. Is there a way to tell the browser to pause the script so that it can resume its foreground / user interface? Something like that?:

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

thanks

+6
javascript
source share
5 answers

If you want it to sleep, you start it at intervals:

 var i = 0; var jobInterval = setInterval(bigJob, 1000); function bigJob() { somework(); i++; if(i>1000000) { clearInterval(jobInterval); } } 

You will need to track the number of iterations in the function and kill the interval when you are done.

If the someWork () function is intense, you will still depend on the browser at each interval.

+2
source share

Possible ways:

  • separate window
  • work fragments alternating with a timer
  • HTML5 Workflows
  • NPAPI Plugin
  • Extension

It all comes down to your requirements and limitations.

+3
source share

You can do something like:

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

This will execute your piece of code every 100 ms.

+2
source share

You can run a long job in the background.

Here is a very small library that allows you to do this: http://adambom.imtqy.com/parallel.js/

It also uses all the processing power because it appears on all processor cores in the background.

Sample for setting 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); 

Example for multi-core:

 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 reserve for using timeouts if the browser does not support workers.

+1
source share

If pop-ups and such are enabled in the browser, you can open a new window outside the viewport and execute its script.

0
source share

All Articles