-1

I wanted to test the execution time of console.log, but whatever number I set as the delay for setTimeout, it is still executed after console.log. I don't understand why so.

function first() {
    console.log("This should be printed first");
}

setTimeout(first, 0.00001);

console.log("This should be printed second");
fitipct
  • 11
  • 1
  • How would `setTimeout` help you learn about the execution time of `console.log`? And why do you want to do this anyway? What do you want to do with this information? – Felix Kling Dec 16 '21 at 10:21

1 Answers1

2

From MDN:

delay Optional
The time, in milliseconds that the timer should wait before the specified function or code is executed. If this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. Note that in either case, the actual delay may be longer than intended; see Reasons for delays longer than specified below.

No matter how small the delay, the first function is going to be put on a queue and not looked at until the current event cycle (which is in the middle of running the current function) has finished (which won't be until after the last console.log statement has been executed).

Further reading:

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335