JavaScript countdown using localStorage

#javascript #stackoverflow

Written by Anders Marzi Tornblad

New StackOverflow user Pankaj Badera asked how to create a simple JavaScript timer that would survive reboots of the user's computer.

For the specific question, this is not a good idea, because it seems as if the problem needs to deal with some sort of timing rules (school assignment deadlines, maybe?), in which case a server-side solution is a must. However, the technical aspects is pretty intriguing. I have faced this problem before, for a couple of different projects.

In principal, you can start any type of countdown, or "countup", allowing the counter to continue between browser and computer restarts, by recording the current time for when an event starts (by calling Date.now()), and then continuously checking the difference between that saved value and the current time of a later event.

My answer looks like this:

(function() {
    var started = localStorage['started'];

    if (started) {
        // This is not the first time the user visits this page
        // How long has it been?

        var diff = Date.now() - started;

        if (diff >= 1000 * 60 * 60 * 24 * 7) {
            // At least one week has passed. Do something here.
        } else {
            // Less than a week has passed. Do something else here.
        }
    } else {
        // This is the first time the user visits this page

        localStorage['started'] = Date.now();

        // Do something else here to welcome the user...
    }
})();

It's important to rembember that you have very little control over this solution, though. You are doing this on the user's browser, and the user has full control over that environment. A simple clear cache will delete the stored values from localStorage.

Date.now reference: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now