How does setInterval and setTimeout work?

Taron Mehrabyan picture Taron Mehrabyan · Feb 26, 2014 · Viewed 23.5k times · Source

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, and that you can simulate asynchronous execution using setInterval and setTimeout functions,

but when I thought about how they can work I couldn't clearly understand it. So how these functions affect execution context?

I suppose that in specific time runs only one part of the code and after it switches to another part. If so, then would a lot of setInterval or setTimeout calls affect performance?

Answer

CDT picture CDT · Apr 1, 2015

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.