How does setInterval and setTimeout work?

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.

Leave a Comment