Skip to content

Explain multiple setIntervals with same time.

twitter logo github logo ・1 min read  

Since JavaScript is single threaded, if I set two time intervel to run 2 functions with same time. Will it execute 2 functions or just one?

For example I have set two set intervals to run two function every 30 minutes.

Or it'll queue two functions for execution?

twitter logo DISCUSS (4)
markdown guide

It will execute both but how... that it depends.

Exactly because it's single threaded and with an event loop is practically impossible to set two timers with the same delay to trigger at the same time: one will always trigger before the other.

Keep in mind that setInterval does not exactly say: "hey, run this function exactly every x milliseconds at all costs" but it says "hey, put this function to be executed in the queue every x milliseconds" which is a subtle difference.

If the browser is processing other events when the clock fires than the setInterval will be delayed and it can also be dropped if there's another timer scheduled for execution in that exact instant or they can fire without respecting the interval.

A really good explanation by John Resig:


Setting an interval adds the task to JavaScript's event loop, so both functions should run one after the other if I understood your question correctly.

Classic DEV Post from Jun 24 '19

How do you handle unproductive days at work?

help to boost productivity and motivation

Sathish profile image
Developer, SkcriptHQ. Codes without coffee. I work on NodeJS, ReactJS, Ruby on Rails by day & Rust lang by night.