Error in JavaScript setInterval

2

I have a problem, I have performed a function that executes a setInterval .

The first time the function was called works correctly (every second) but when I call it several times, the time goes out as if it were executing the setInterval of previous calls.

How can you reset the time so that it always works a second?

function ejecutar_timer(){
  var valor = 0;
  clearInterval(timerId);
  timerId =  setInterval(function(){
    valor = valor + 1;
  }, 1000);
}
    
asked by Luis Alberto Aguilera Clarke 01.04.2016 в 18:21
source

2 answers

3

The idea is that you use setInterval and save your ID so that you can then stop it when you want using clearInterval . You can achieve this with a global variable.

I'll give you an example using two buttons:

var timerId = false;

function ejecutarTimer(){
    var valor = 0;
    // Para evitar que se ejecute nuevamente si ya está corriendo
    if (!timerId) {
        timerId = setInterval(function(){
            valor = valor + 1;
            document.getElementById("contador").innerHTML = valor;
        }, 1000);
    }
}

function detenerTimer() {
    clearInterval(timerId);
    timerId = false;
}
<button onclick="ejecutarTimer()">Iniciar</button>
<button onclick="detenerTimer()">Detener</button>
Contador: <span id="contador">0</span>

Notice, I'm validating that the timer is not running before creating a new one:

if (!timerId) {
    // ...
}

And that the timer is resetting it to false each time the detenerTimer function is executed

    
answered by 01.04.2016 / 18:39
source
1

SetInterval executes the function EACH x milliseconds, it should only be executed once, so that it is executed only once or to recursively use it is setTimeout. Then, think that the value variable is inside the function execute_timer, it can not be accessed from outside.

    
answered by 01.04.2016 в 18:38