posted 7 years ago
Timers are used for many things in JavaScript. From simple "make something happened in 2 minutes" to breaking up computationally intensive operations.
JavaScript is single-threaded. So when some computationally intensive operation is underway, it "hogs" the execution queue. Timers can be used to execute the operation in chunks to let other operations get into the execution queue,
Interval timers can be used to schedule operations to occur at set intervals of time. For example, refreshing the data on the page using Ajax once every minute.
Because JavaScript is single threaded, knowing exactly how timers and intervals act can get complex if things get busy. For example, what happens if a timer goes off while another is processing its callback? What happens to intervals if the execution queue is busy while a timer or another interval fires? What happens if multiple timers or intervals all go off at the same time?
The Taming Timers chapter of Secrets of the JavaScript Ninja explains exactly how timers and intervals work, and how they react in the single -threaded environment of JavaScript when there is contention for the execution queue.