Question

i have a simple clock that counts the amount of seconds passed for an AJAX call to be completed. Each request takes a different time frame and different requests can be made on the same page without refreshing.

I am using jquery to show a timer of the current request but i cannot figure out a way to clear the timer back to 0 for every new request.

$(document).ready(function(){
    $('#startTimer').click(function(){
    var sec = 0;
    var siID = setInterval(function() {$('#counter span').text(++sec);}, 1000);
    })
});

JSFIDDLE: clicky clicky

the problem can be replicated my pressing the 'START' button again after you press it the first time. You will see a second counter beginning from 0 while at the same time the initial counter will continue to increment and display.

What i need is either:

1-have the start button be able to be pressed again and restart clean from 0 every time

2-have the stop and reset button be able to be pressed to reset the counter back to 0 then press the start button to begin a new clean counter

What i DONT want:

1 - a counter in the function that ends it after certain seconds if(sec == 20){die();}; each request is a different length of time so this will not work

2 - to run another function and have the timers silently run in the background until the page is reloaded

I played around with clearInterval() and couldn't get anything to work...

Thank you for your time and advice!

Was it helpful?

Solution

Try this as a starting point:

var siID;
$(document).ready(function(){
    $('#startTimer').click(function(){
    var sec = 0;
    siID = setInterval(function() {$('#counter span').text(++sec);}, 1000);
    })

    $('#stopTimer').click(function() {
        window.clearInterval(siID);
        $('#counter span').text('0');
    });
});

http://jsfiddle.net/GNrUM/735/

Your variable siID is declared inside the click handler, therefor it no longer exists after the function exits and you can't use clearInterval with it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top