Javascript execution order with setTimeout()

北城以北 提交于 2020-01-01 08:53:15

问题


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



来源:https://stackoverflow.com/questions/4861050/javascript-execution-order-with-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!