title: Async behaviour in javascript
body: <p>Consider the following javascript algorithm:</p>
  
  <pre><code>for(var i = 0; i &lt; 50; i ++){
      console.log('starting :', i);
      getPrimes(1000000);
      (function(i){
          setTimeout(function(){
              console.log('done :', i);
          }, 1000);
      })(i);
  }
  
  function getPrimes(max) {
      var sieve = [], i, j, primes = [];
      for (i = 2; i &lt;= max; ++i) {
          if (!sieve[i]) {
              // i has not been marked -- it is prime
              primes.push(i);
              for (j = i &lt;&lt; 1; j &lt;= max; j += i) {
                  sieve[j] = true;
              }
          }
      }
      return primes;
  }
  </code></pre>
  
  <p>The for loop launches getPrimes function that takes some time and then runs another function that has timeout of one second. Thinking about this algorithm what I will be expecting to get on the console is a mix between "starting" and "done" lines ordered from start to end but not necessarily sorted from 1 to 50. </p>
  
  <p>In reality what I get is 50 lines of "starting" (that take some time to process) and then immidiatelly 50 lines of "done". </p>
  
  <p>My question is why? The logic tells that while running the for loop at least one timout callback should be finished and because javascript is single threaded asynchronous it should display a line of "done" in between some lines of "starting"</p>
  
  <p>Could it be because the primes calculation takes all the cpu power?</p>
  
  <p>Thanks</p>