Question about setTimeout that I need answer to

后端 未结 3 1966
你的背包
你的背包 2021-01-20 22:20

So we all know setTimeout waits a certain amount of time before executing something. My question is, does it wait for the above code to finish executing first, before waitin

3条回答
  •  粉色の甜心
    2021-01-20 22:36

    JavaScript is single-threaded and non-preemptive, it's not possible to interrupt code that's running. Asynchronous code, such as timeouts and AJAX callbacks, cannot run until the currently executing code returns to the main event loop.

    The timer in setTimeout starts immediately when it's called. But because of the single-threaded design, the callback can't be called until all your current JS finishes. If that takes longer than the timer, then the callback will be delayed. So all you're guaranteed is that the callback will be called in at least that amount of time -- it might be longer, but not shorter. There could also be other asynchronous callbacks ahead of it in the event queue.

提交回复
热议问题