Consider the following javascript algorithm:
for(var i = 0; i < 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 <= max; ++i) {
if (!sieve[i]) {
// i has not been marked -- it is prime
primes.push(i);
for (j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return primes;
}
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.
In reality what I get is 50 lines of "starting" (that take some time to process) and then immidiatelly 50 lines of "done".
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"
Could it be because the primes calculation takes all the cpu power?
Thanks