Josh Josh - 1 month ago 12
Javascript Question

Timing in JS - multiple setIntervals running at once and starting at the same time?

Let's say I have a function:

myFunc = function(number) {
console.log("Booyah! "+number);
}


And I want it to run on a set interval. Sounds like I should use setInterval, huh!

But what if I want to run multiple intervals of the same function, all starting at the exact same time?

setInterval(function(){
myFunc(1);
}, 500);

setInterval(function(){
myFunc(2);
}, 1000);

setInterval(function(){
myFunc(3);
}, 2000);


So that the first runs exactly twice in the time it takes the second to run once, and the same between the second and third.

How do you make sure that they all start at the same time so that they are in sync?

Answer

Good question, but in JS you can't. To have multiple functions in the same program execute at the same time you need multi-threading and some deep timing and thread handling skills. JS is single threaded. setInterval doesn't acutally run the function after the delay, rather after the delay it adds the function to the event stack to be run as soon as the processor can get to it. If the proc is busy with another operation, it will take longer than the delay period to actually run. Multiple intervals/timeouts are all adding calls to the same event stack, so they run in turn as the proc is available.