0

Here is my code. Is there any way to make my javascript time wont reset when the user refreshes the browser ?

function startTimer(duration, display) {
        var timer = duration,
            minutes, seconds;
        setInterval(function() {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

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

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

            if (--timer < 0) {

                document.getElementById("testik4").submit();
            }
        }, 1000);
    }

    window.onload = function() {
        var fiveMinutes = 60 * 18,
            display = document.querySelector('#time');
        startTimer(fiveMinutes, display);
    };
<span id="time"></span>
Sudhir Ojha
  • 3,009
  • 2
  • 11
  • 23
Yuyun
  • 1
  • 1
    The best way is to save the last value in a cookie. When the page loads, check if cookie exists and read its value, else start it with your defaul value: 5 minutes. – besciualex Jan 29 '20 at 12:33
  • https://stackoverflow.com/questions/3220660/local-storage-vs-cookies – Pinguin Dirk Jan 29 '20 at 12:34
  • I recommend localStorage probably – TKoL Jan 29 '20 at 12:35
  • 2
    In the case of a timer counting down to a specific time, I would store the time being counted down to and use the interval to just update the display of the time between now and then. – phuzi Jan 29 '20 at 12:35
  • 1
    BTW, subtracting `1` from `timer` every second is an insane way to code a countdown. It's far from guaranteed that your `setTimeout` callback will be executed *exactly* every 1000ms, so you'll get drift over time. You need to store a start or stop time `Date` value, and on every iteration compute the difference between that value and now instead. – deceze Jan 29 '20 at 12:36
  • OT: `var fiveMinutes = 60 * 18` 60 * 18 is 18, not 5, minutes. – phuzi Jan 29 '20 at 12:38

2 Answers2

0

Here is a simple working example which uses cookies to keep the timer value on client browser. Please read the comments to understand the code better. Because StackOverflow does not allow usage of cookies in Code Snippets, I wrote a code sample instead of a snippet. Copy-paste it on your web page and test it.

Feel free to ask in comments if anything is unclear. Someone also suggested to use LocalStorage. That's an option too, the main difference between Cookies and LocalStorage in this case would be that cookies can be read by server too.

// Copied from https://www.w3schools.com/js/js_cookies.asp
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}


window.addEventListener('DOMContentLoaded', function() {

    let timer = 60 * 18, // default value
        display = document.querySelector('#time'),
        // set cookie name and read its value
        // empty string means is not set
        cname = 'my_timer',
        cvalue = getCookie(cname);

    // If there is something in cookie, overwrite default value
    if (cvalue != '') {
        timer = parseInt(cvalue);
    }

    setInterval(function() {

        let minutes = parseInt(timer / 60, 10),
            seconds = parseInt(timer % 60, 10);

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

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

        // Update cookie value
        document.cookie = cname + '=' + timer;

        if (--timer < 0) {
            document.getElementById("testik4").submit();
        }
    }, 1000);
});
besciualex
  • 1,747
  • 1
  • 13
  • 20
-2

you can use session/local storage or cookies.If you set session/local storage or cookies then not reset time.