Search code examples
javascriptmemory-managementloopsfor-loopcpu-usage

How to calculate that to what maximum number of times for loop can run in Javascript?


In Javascript, if we have the following code:

var j = 0;

for(i=0; i<j; i++){
  //JS Code
}

In this code, on what factors the maximum value of variable j (that is the value upto which browser will not hang) will depend upon (like may be Machine's RAM or Processor or may be the code being executed in the loop)?

And can this maximum permissible value calculated?

This is required as there is a large array which needs to be processed.

Thanks for any suggestions in advance.


Solution

  • No, you can't calculate this, it varies too much from browser to browser. Some browsers do it by time (e.g., your code has run for more than X seconds without yielding back to the browser; on Firefox 7 the default is 10 seconds but the user can change it), other browsers do it by number of operations (IE, for instance).

    Your best bet is to refactor your code so you avoid even beginning to approach the limit. If you have a large piece of work to do, break it into chunks, then run the chunks one after another using setTimeout with a timeout value of 0. This yields back to the browser (for more than 0 milliseconds; exactly how long will vary by browser and by what other things are going on on the page).

    Here's an example of counting to 10,000,000 in 100,000 iteration chunks:

    function toAMillion() {
      var counter = 0,
          limit = 10000000,
          chunk = 100000;
    
      doAChunk();
    
      function doAChunk() {
        var target = Math.min(limit, counter + chunk);
    
        while (counter < target) {
          ++counter;
        }
    
        if (counter < limit) {
          // Schedule next chunk
          setTimeout(doAChunk, 0);
        }
        else {
          // Done
          display("Done, counter = " + counter);
        }
      }
    }
    

    Live copy