Izion
Izion

Reputation: 770

Javascript count up from page load - need to reset with ajax

I'm not too good with Javascript and Im having a little trouble resetting a counter that I have found here on stack, here is the counter:

var pageVisisted = new Date(); // you should probably store this in a database/attach it to the session or AT LEAST in a cookie


setInterval(function() {
    var timeOnSite = new Date() - pageVisisted;

    var secondsTotal = timeOnSite / 1000;

    var seconds = Math.floor(secondsTotal);

    document.getElementById('time').innerHTML = seconds;
}, 1000);

I have tried the following from reading other questions on here:

function stop_time(){
  clearInterval(timeOnSite);
}

This does start the counter again but it created two counters switching from one to the other.

All I would like to do is when the user clicks 'Update' the counter will set back to 0 and start again (and also update the data on the page which is already working).

Any advice or reading material would be much appreciated.

Thanks

Upvotes: 1

Views: 550

Answers (1)

Mike H.
Mike H.

Reputation: 1751

You need to assign your interval to a variable in order to clear it properly

function myFn() {
    var timeOnSite = new Date() - pageVisisted;
    var secondsTotal = timeOnSite / 1000;
    var seconds = Math.floor(secondsTotal);

    document.getElementById('time').innerHTML = seconds;
}

var myTimer = setInterval(myFn, 4000);

Then to reset it, clear with the variable as a parameter and start it again.

clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);

Upvotes: 2

Related Questions