-1

I am showing a minutes/seconds counter for each question in a test (It doesn't always start from 0 because the user can return to a question).

The user navigates to the next question via ajax.

My problem is that after the first question JS also remembers the values from the previous questions.

The value that returns from the ajax call is ok.

<script>


$.ajax({
    type    : "POST",
    cache   : false,
    url     : "/ajax/Get_test_question",
    data: post_data,
    success: function(sec) {             
        show_timer(sec);        
    }
})


function pad(val) {
    return val > 9 ? val : "0" + val;
}   
function show_timer(sec) {  
        timer=setInterval(function () {
            console.log(sec)
            $("#seconds_counter").text(pad(++sec % 60));
            $("#minutes_counter").text(pad(parseInt(sec / 60, 10)));

    }, 1000);
}

</script>    
Musa
  • 96,336
  • 17
  • 118
  • 137
user3553470
  • 107
  • 9
  • 1
    My problem is that after the first question JS also remembers the values from the previous questions. How is that a question? – void Dec 27 '15 at 18:25
  • Possible duplicate of [Stop setInterval call in JavaScript](http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript) – JJJ Dec 27 '15 at 18:30

1 Answers1

0

You should destroy the interval object as soon as you are displaying next question before before starting interval for next question.

var timer;
function show_timer(sec) { 
    if(timer) {
        clearInterval(timer);
    }

    timer=setInterval(function () {
        console.log(sec)
        $("#seconds_counter").text(pad(++sec % 60));
        $("#minutes_counter").text(pad(parseInt(sec / 60, 10)));

    }, 1000);
}
Scarecrow
  • 4,057
  • 3
  • 30
  • 56