简体   繁体   中英

Javascript timer page refresh

I have a timer set to countdown from 10 minutes. I need it so when the user refreshes the page it does not reset the timer. Here is my javascript.

function startTimer(duration, display) {
var start = Date.now(),
    diff,
    minutes,
    seconds;
function timer() {
    // get the number of seconds that have elapsed since 
    // startTimer() was called
    diff = duration - (((Date.now() - start) / 1000) | 0);

    // does the same job as parseInt truncates the float
    minutes = (diff / 60) | 0;
    seconds = (diff % 60) | 0;

    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;

    display.textContent = minutes + ":" + seconds; 

    if (diff <= 0) {
        // add one second so that the count down starts at the full     duration
        // example 05:00 not 04:59
        start = Date.now() + 1000;
    }
};
// we don't want to wait a full second before the timer starts
timer();
setInterval(timer, 1000);
}

window.onload = function () {
var fiveMinutes = 60 * 10,
    display = document.querySelector('#time');
startTimer(fiveMinutes, display);
};

It's 2019. I'd highly suggest using localStorage or sessionStorage instead of cookies.

const start = localStorage.getItem('startTime') || Date.now();
// ...rest of your code...
window.onload = function() {
    localStorage.setItem('startTime', start);
    // ...rest of your code...
};

You may want to put the localStorage.setItem bit inside your startTimer function, after you set the value of start . Depends on the details of what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM