setInterval
returns a timeoutID that is used to identify it.
To stop a setInterval
you pass it's timoueID to clearInterval
.
Explanation of why you get two intervals running
When you do this:
intervals[idVar] = setInterval(function() { update(); }, 1000);
intervals[idVar] = setInterval(function() { update(); }, 1000);
What you are doing is:
call your first setInterval
and setting intervals[idVar]
to this first setInterval's
timeoutID
call your second setInterval
and overwrite the value stored in intervals[idVar]
with the timeoutID of your newly called
setInterval
Result: Two seperate intervals, with intervals[idVar]
storing the timeoutID of the second one called
setTimeout
setTimeout is like setInterval and actually uses the same pool of timeout IDs, but it is only invoked once after the specified delay.
Setting one interval (setTimeout or setInterval) per idVar
var idVar = setInterval(function() {
update();
}, 1000); // sets idVar to the timeoutID and starts the interval
}
intervals[idVar] = idVar; // assigns a property 'idVar' on `intervals`
// and sets the timeoutID as its value
// allows you to call clearInterval(intervals[idVar]);
However, without knowing exactly what your update()
method is doing it is difficult to tell what the best solution would be here...