Javascript execution order with setTimeout()

2020-07-06 06:07发布

问题:

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 :(

回答1:

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 ;)