0

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?

2 Answers 2

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.