DEV Community

Sathish
Sathish

Posted on • Edited on

2 2

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

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Discover fresh viewpoints in this insightful post, supported by our vibrant DEV Community. Every developer’s experience matters—add your thoughts and help us grow together.

A simple “thank you” can uplift the author and spark new discussions—leave yours below!

On DEV, knowledge-sharing connects us and drives innovation. Found this useful? A quick note of appreciation makes a real impact.

Okay