-2

Does the setTimeout() function wait until the function inside of it is executed before moving on to the next line (the line AFTER "setTimeout()")? OR, does setTimeout() just parse through the code while setting the timer for the function to be activated after "x" amount of time? I ask this because I don't know if the "setTimeout()" function just finishes itself by setting a timer for another function before moving on (the function within "setTimeout()" doesn't have to be completed to move on), OR if the "setTimeout()" function stops the next line from executing until "setTimeout()'s" function is completed.

Mangofett
  • 111
  • 9
  • 3
    This is a duplicate: http://stackoverflow.com/questions/10258012/does-javascript-settimeout-stop-other-script-execution – symlink Apr 17 '16 at 22:19

3 Answers3

2

It does not wait. The timer starts, then next line is executed, then sometime later setTimeout function fires

Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
2

No, setTimeout does not block execution of the next line. It sets up a function to be called after the given timeout expires.

Run the snippet below for a demo:

setTimeout(function() {
  document.getElementById('log').innerHTML += 'timeout!!<br>';
}, 1000);

document.getElementById('log').innerHTML += 'hello world<br>';
<div id="log"></div>
0

setTimeout() is asynchronous so the next line will be executed immediately

Richard Guy
  • 470
  • 4
  • 12