0

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.

Dophin
  • 23
  • 4

1 Answers1

0

In the first function, you start the timer then execute the loop in parallel to the timer. In the second function, you start the timer after finishing the loop (serially)

AhmadWabbi
  • 2,253
  • 1
  • 20
  • 35
  • Yes, but in both cases the code started at the setTimeout(count1,0) is executed after the rest of code (the loop) is ended. (if I correctly understand how the setTimeout(..,0) method works) – Dophin Dec 04 '17 at 12:15
  • No. The timer of `setTimeout` starts immediately when the function `setTimeout` is called, not at the end of the calling function-call. – AhmadWabbi Dec 04 '17 at 12:42
  • Based on the doc: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout "value of 0 is used, meaning execute "immediately", or more accurately, as soon as possible". "As soon as possible" in the current context means right after the loop is finished (not in parallel). Am I wrong? – Dophin Dec 05 '17 at 05:53
  • Ah, I didn't see the 0 as time. But still, the minimum timeout value is between 4ms and 10 ms (https://stackoverflow.com/questions/9647215/what-is-minimum-millisecond-value-of-settimeout). When you call `setTimeout` at the end, you loose this time, multiplied by the number of calls. It sums up. – AhmadWabbi Dec 05 '17 at 08:47