DEV Community

Sathish
Sathish

Posted on • Edited on

Explain multiple setIntervals with same time.

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?

Top comments (4)

Collapse
 
rhymes profile image
rhymes • Edited

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: johnresig.com/blog/how-javascript-...

Collapse
 
nestedsoftware profile image
Nested Software

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.

Collapse
 
sathish profile image
Sathish

Yup! Got it. Thanks.

Collapse
 
itsjzt profile image
Saurabh Sharma

Well for better understanding see this youtu.be/8aGhZQkoFbQ