I have a problem, I have made a function that executes a setInterval
.
The first time the function is called it works fine (every second) but when I call it several times, the time goes haywire as if it was executing the ones setInterval
from the previous calls.
How can you reset the time so that it always works to one second?
function ejecutar_timer(){
var valor = 0;
clearInterval(timerId);
timerId = setInterval(function(){
valor = valor + 1;
}, 1000);
}
The idea is that you use
setInterval
and save its ID so that later you can stop it whenever you want usingclearInterval
. You can achieve this with a global variable.I leave you an example using two buttons:
Note that I am validating that the timer is not previously running before creating a new one:
And that I am resetting the timer
false
every time the function is executeddetenerTimer
SetInterval executes the function EVERY x milliseconds, it should only be executed once, to be executed only once or to use it recursively it is setTimeout. Then think that the variable value is inside the run_timer function, it can't be accessed from outside.