12

Say that I have the following code:

function testA {
   setTimeout('testB()', 1000);
   doLong();
}

function testB {
   doSomething();
}

function doLong() {
   //takes a few seconds to do something
}

I execute testA(). I have read that Javascript is single-threaded. What happens after 1000 milliseconds, when the timeout for testB() is reached?

Some possibilities I can think of:

  • testB() is queued up to execute after doLong() and anything else it called have finished.
  • doLong() is immediately terminated and testB() is started.
  • doLong() is given a little while longer to execute before being stopped (either automatically or after prompting the user) and testB() is started.
  • doLong() is paused, testB() is started. After testB() has finished, doLong() resumes.

What is the correct answer? Is it implementation dependant or part of the standard?*

This question is similar but not the same, as far as I can tell.

Any links that you can recommend for better understanding Javascript execution would be appreciated.

Thanks!

*Yes, I know that not all browsers follow standards :(

Community
  • 1
  • 1
Brian Beckett
  • 4,742
  • 6
  • 33
  • 52

1 Answers1

11

The first of your guesses is the correct one: testB() is queued up to execute after doLong() and anything else it called have finished.

If it takes more than one second for testA to finish, testB will simply have to wait.

Also, you should write setTimeout(testB, 1000) rather than setTimeout('testB()', 1000). Sending a string to setTimeout is, like using eval, generally considered evil and will make you enemies ;)

Community
  • 1
  • 1
Jakob
  • 24,154
  • 8
  • 46
  • 57
  • I came to believe `setTimeout(function() { testB(); }, 1000);` is the best way, were I misled? – Shadow The GPT Wizard Feb 01 '11 at 10:07
  • 2
    @Shadow Wizard: Yes, pretty much misled. As far as I know there's no difference between your way and mine (except that mine is shorter of course :D). To illustrate, imagine if we pulled out your expression into a variable: `var f = function() { testB(); }; setTimeout(f, 1000);`. Still the same meaning, but now you can see the redundancy. – Jakob Feb 01 '11 at 10:13
  • 1
    Thank you, both for the answer and for the advice about passing a function to setTimeout instead of a String. Looks like the tutorials I've been reading are a little dubious ;) – Brian Beckett Feb 01 '11 at 10:41
  • As with the latest chrome(ver. 62), this is not the case. testB() will executed first and then doLong() will be executed. – coderz Oct 24 '17 at 10:58