views:

87

answers:

5

I'd like to run some calculations in a browser window, but I don't want it to slow the client computer down for user interaction, especially for single core machines. Is there some way to adjust the nice level of my executing JavaScript so that it will execute as fast as possible without detracting from the responsiveness of the machine?

+3  A: 

I can't think of anything else than delaying execution of your calculations. In example, dividing all work into small pieces and then running them sequentially with some delay (using setTimeout or setInterval) between each task.

miensol
+2  A: 

For speed attempt to use a single multidimensional array to contain your data and then at the end of your function use a single join to convert that array to a string for output and output that data using the innerHTML method. That is the fastest possible method of containing and serving data in JavaScript. Definitely do not use DOM methods or elements to output your data as that is about 4 times as slow.

Output your data as few times as possible. This is going to be determined upon which event you use to execute your function. I recommend not using the onload event as this will slow the initial load time of your page. I would recommend using the onclick function associated with a button, because then the user is aware that they caused the execution that is slowing down your page.

+1  A: 

I did some testing, and the browser needs quite some time between bursts of work to be reasonably responsive:

function work(cnt) {
  // do some heavy work
  for (var i=0;i<100000000;i++) ;
  // start next work
  if (cnt > 0) {
    window.setTimeout(function(){work(cnt-1);},200);
  }
}
Guffa
+2  A: 

Create open loops... an example

This is a close loop

for( i = 0 ; i < 10000 ; i++)
{
    doSomeMath(i);
}

This is an open loop

i = 0;
iMax = 10000
var MyWorkingThread =
setInterval(function()
{
    if( i < iMax)
    {
       doSomeMath(i);           
       i++;
    }
    else
    {
        clearInterval(MyWorkingThread);
    }

},1);

You can make a more, or a less work inside the open loop, but this is the general idea. I have made this many times for similar issues and I left the browser work very smooth.

Aristos
A: 
  1. run the calculation on the server with an ajax request
  2. open a new window or frame and run the code there
  3. run the code in a loop broken into intervals
  4. be ready to use web-worker processes (html5 asynchronous script)
kennebec
?? If he's using web workers, why would he offload the processing to the server?
Pierreten