How does setInterval and setTimeout work?

后端 未结 5 977
一向
一向 2020-11-30 00:57

I was in an awkward situation,

I am working with pure JavaScript for almost 3 years, and I know that JavaScript is single-threaded language

5条回答
  •  执念已碎
    2020-11-30 01:08

    Javascript is singled-threaded but the browser is not. The browser has at least three threads: Javascript engine thread, UI thread, and timing thread, where the timing of setTimeout and setInterval are done by the timing thread.

    When calling setTimeout or setInterval, a timer thread in the browser starts counting down and when time up puts the callback function in javascript thread's execution stack. The callback function is not executed before other functions above it in the stack finishes. So if there are other time-consuming functions being executed when time up, the callback of setTimeout will not finish in time.

提交回复
热议问题