Adelov
Adelov

Reputation: 395

How to make my countdown timer don't start from the beginning when refreshing the page

I got a countdown code from this repository and i made some changes, and i want to make the countdown don't start from the beginning when i refresh the page, my Js code is :

var timeleft =5400;

var startTime = 0;
var currentTime = 0;

function convertSeconds(s) {
    var decimal = (s/3600) - Math.floor((s/3600))
    var h = floor(s/3600);
    var min = floor(decimal * 60) ;
    var sec = s % 60;
    return nf(h, 2) + ':' + nf(min, 2) + ':' + nf(sec, 2);
}

function setup() {
    noCanvas();
    startTime = millis();

    var timer = select('#timer');
    timer.html(convertSeconds(timeleft - currentTime));

    var interval = setInterval(timeIt, 1000);

    function timeIt() {
        currentTime = floor((millis() - startTime) / 1000);
        timer.html(convertSeconds(timeleft - currentTime));
        if (currentTime == timeleft) {
            clearInterval(interval);
        }
    }
}

My HTML code :

<html>
<head>
    <meta charset="UTF-8">
    <script language="javascript" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/p5.js"></script>
    <script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.dom.js"></script>
    <script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.6.1/addons/p5.sound.js"></script>
    <script language="javascript" type="text/javascript" src="chrono.js"></script>
</head>
<body>
    <p id="timer"></p>
</body>
</html>

Upvotes: 0

Views: 177

Answers (1)

T McKeown
T McKeown

Reputation: 12847

You could store the current counter value to local storage (cookie or other options if using html 5) and upon load of the page read it's value and start your timer based on that.

Andrew suggested storing a timestamp every time the interval begins to storage. Then upon load you get the delta by subtracting the current timestamp by the stored timestamp

Upvotes: 1

Related Questions