It accelerates from inside because of this:
function looper () {
// stuff
callLooperIn1Second();
}
function cycle () {
// stuff
looper();
callCycleIn5Seconds();
}
Looper will call itself every second.
Cycle will call a looper every 5 seconds, which will call itself every second.
So every 5 seconds, cycle
calls looper
again, and it adds to the times it is scheduled to run. You add to the number of times looper
gets called that second.
When you first call cycle
, looper
will run once per second.
After 5 seconds, it will run 2x per second.
After 10 seconds, it will run 3x per second.
cycle // call looper, which schedules every 1s
looper
looper
looper
looper
looper
cycle // call looper, which schedules every 1s
looper looper
looper looper
looper looper
looper looper
looper looper
cycle // call looper, which schedules every 1s
looper looper looper
looper looper looper
looper looper looper
looper looper looper
looper looper looper
Switching this to use setInterval would not work, because then you're just causing cycle
to setInterval
on looper
every 5 seconds, which is slightly less code to accomplish the same problem.
I would recommend breaking your flow and scheduling code away from the thing that you actually intend to do.
let currentSecond = 0;
const totalSeconds = 120;
const sites = ["a", "b", "c"];
const totalSites = sites.length;
let siteIndex = 0;
function looper (i) {
currentSecond = (i + 1) % totalSeconds;
}
function cycle (i) {
const site = sites[i];
siteIndex = (i + 1) % totalSites;
}
function triggerLoop () {
const loopDelayMS = 1000;
looper(currentSecond);
setTimeout(triggerLoop, loopDelayMS);
}
function triggerCycle () {
const cycleDelayMS = 5000;
cycle(siteIndex);
setTimeout(triggerCycle, cycleDelayMS);
}
function run () {
triggerLoop();
triggerCycle();
}
You could take this much further, of course.
You could run those things on separate intervals, rather than on recursive timeouts. That would be fine.
You could make the processes more dependent upon one another, and that's fine, too... except that you would need to add a lot more timer-management code, to figure out how far along looper
is, in its counting, and what that means for cycle
every time it's fired.
It doesn't look like those two counters are attached to one another in any possible way. You want one to count every second in 2 minutes, and you want the other to count every 5 seconds, for as long as there are elements in an array, and you want both of them to reset and keep going, when they hit their limit. So as far as I can tell, the timers have nothing to do with one another. It's just the fact that they're tied up in the code that has them misbehaving.