NiklasOvermark
NiklasOvermark

Reputation: 39

How do i make timer reset when user leave website

I've done a timer that counts up in javascript. The idea is to show the user how long it has been on the website. I want it to show the time regardless of when the user jumps between different pages on the website but when the user leaves or closes the tab it should be reset. My problem is that even if i close down the browser, it continues where i left it. JavaScript

var countDownDate = localStorage.getItem('startDate');
if (countDownDate) {
    countDownDate = new Date(countDownDate);
} else {
    countDownDate = new Date();
    localStorage.setItem('startDate', countDownDate);
}
// Update the count down every 1 second
var x = setInterval(function () {

    // Get todays date and time
    var now = new Date().getTime();

    // Find the distance between now an the count down date
    var distance = now - countDownDate.getTime();

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    // Output the result in an element with id="demo"
    document.getElementById("timer").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
}, 1000);

HTML

<body>
    <p id="timer"></p>
</body>

Upvotes: 1

Views: 348

Answers (2)

NiklasOvermark
NiklasOvermark

Reputation: 39

Change localStorage to sessionStorage solved the problem

Upvotes: 1

xdeepakv
xdeepakv

Reputation: 8125

You can use window unload api to clean up the things on last window close.

<body onunload="cleanUp()">

function cleanUp() {
  localStorage.setItem('startDate', null);
}

Upvotes: 0

Related Questions