Javascript timer clearInterval

23 Views Asked by At

I have this Javascript code:

function resetTimerAndSaveExam(){
    clearInterval(x);
}

if($('#exerciseTipology').val() === "exam"){
    var totalMinutes = $('#totalMinutes').val();
    var time = 60 * totalMinutes; // This is the time allowed

    var saved_countdown = localStorage.getItem('saved_countdown');

    if(saved_countdown == null) {
        var new_countdown = new Date().getTime() + time * 1000;
        time = new_countdown;
        localStorage.setItem('saved_countdown', new_countdown);
    } else {
        time = saved_countdown;
    }

    var x = setInterval(() => {

        var now = new Date().getTime();
        var distance = time - now;
        var timeLeft = millisToMinutesAndSeconds(distance)

        if ($('#timeRemaining').length){
            document.getElementById("timeRemaining").innerHTML = timeLeft;
        }

        if (distance/1000 <= 0) {
            clearInterval(x);
            localStorage.removeItem('saved_countdown');
            $('#timeRemaining').css('color', 'red');
            $('#timeRemaining').html("CONCLUSO");

            location.href = URL + "teoria/saveExam";
        }
    }, 1000);
}

When the timer arrives to 0 it is ok and the timer rese the interval. I have another button, and when I press it I have a onClick function going to resetTimerAndSaveExam, but the clearInterval(x) code doesn't work, the tomer does not reset.

0

There are 0 best solutions below