Anders Tornblad

All about the code

JavaScript countdown using localStorage

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. As it turns out, I have already faced this problem before, when building Tajmkiper, which handles all of its timing client-side.

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

In Tajmkiper, this is done for many projects at the same time, but the principle is the same. In the case of this StackOverflow question, there is only one timer. Also, Tajmkiper is meant to be a tool for the user, and not for keeping track of (from the browser's perspective) externally checked rules like deadlines, so a solution involving local storage is fine.

My answer looks like this:

(function() { var started = localStorage['started']; if (started) { // This is not the first time the user opens this file // 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 opens this file localStorage['started'] = Date.now(); // Do something else here to welcome the user... } })();

For my project time clock, this happens every time you select a different project. I combine this with keeping track of how much time has been clocked total.

Add a comment