I learned JS and stuck with the behavior I can't explain or find answer at the web.
There are two similar functions:
function count1(){
if (i<(1e9+1)-1e6){
setTimeout(count1,0)
}
do{
i++
} while(i%1e6!=0)
if (i==1e9){
console.log('Done1 in '+(Date.now()-start)+'ms')
}
}
function count2(){
do{
i++
} while(i%1e6!=0)
if (i==1e9){
console.log('Done2 in '+(Date.now()-start)+'ms')
}
if (i<(1e9+1)-1e6){
setTimeout(count2,0)
}
}
let start=Date.now();
let i=0;
// count1();
count2();
//why count2 is faster?
</script>
In Chrome the count1 function takes arount 5000 ms, while the count2 takes around 8000 ms. As you can see the only difference is that the "setTimeout" code is located in different places. Would you please help me to understand why so tiny difference in code leads to so huge difference in time consuming.
Thanks in advance.