El Hombre Sin Nombre
El Hombre Sin Nombre

Reputation: 3102

JS - Reset timer when click

I have a 5 minutes countdown. This function launch automatically when page load. I want to reload data of page and resetting this countdown. The code looks like this.

HTML

  <a onClick="timer()" title="Pincha para actualizar" class="pull-right" id="time"></a>

JS

function timer(){
    var timer = 60 * 5, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        $('#time').text("Tiempo restante para actualización de datos " + minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

The problem: When i click the link the timer goes crazy, doesn´t reset properly.

Anybody knows what´s the rigth way to reset countdown?

Upvotes: 0

Views: 1019

Answers (2)

PrakashT
PrakashT

Reputation: 901

you can use clearInterval inside setInterval itself

function timer(){
    var timer = 60 * 5, minutes, seconds;

    interval = setInterval(()=> {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        $('#time').text("Tiempo restante para actualización de datos " + minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }

         if (interval !== null) clearInterval(interval);
    }, 1000);
}

Upvotes: 0

Vincent Valvas
Vincent Valvas

Reputation: 94

You are missing a clearInterval otherwise you are creating a new interval each time you click on the element.

let interval = null;

function timer(){
    var timer = 60 * 5, minutes, seconds;

    if (interval !== null) {
        clearInterval(interval);
    }

    interval = setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        $('#time').text("Tiempo restante para actualización de datos " + minutes + ":" + seconds);

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

Upvotes: 2

Related Questions