Cool123 Cool123 - 11 months ago 28
Javascript Question

How to set a localStorage object as a variable

I wanted to make an app with JavaScript using the localStorage object so I can store information so next time I open the file the info stored from before is still there. I was aiming for some kind of clock of how long you have been on the site for. How could use

localStorage.setItem("example", "variable")
so I could use it as a counter for the clock? Here's one of my test code for this:

<!DOCTYPE html>
<title>Tracking Time</title>
#time {
font-size: 250%
<h1><font face="fantasy">The Time You Have Had This Tab Open</font></h1>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<h1 id="time"><font face="impact" size="10">00:00:00:00:00:00</font></h1>
<script src=""></script>

// Update Count

setInterval(function () {
localStorage.setItem("sec", 0);

}, 1000)


// Update Text

setInterval(function (){
$("#time").text( + " year(s) " + + " month(s) " + + " day(s) " + + " hour(s) " + + " minute(s) " + localStorage.getItem("sec") + " second(s)")
}, 1)


Sorry that it is not complete but I need help for this. Any way I could use it as a variable? Please provide an example. Thanks!


One way of doing this would be to set some kind of "time" property in the local storage if one doesn't exist.

if (localStorage.getItem('time') === null) {
  localStorage.setItem('time', 0);

Then during a loop, you can increment the amount of time saved in the local storage.

var intervalTime = 1000;
setInterval(function() {
  // localStorage saves as strings so lets make it an integer
  var totalTime = parseInt(localStorage.getItem('time'));
  localStorage.setItem('time', totalTime + intervalTime);
}, intervalTime);

This will save the total number of milliseconds the user has spent on your site. You can then use those milliseconds to show how long they've been on the site.

var totalMilliseconds = parseInt(localStorage.getItem('time'));
var totalTime = new Date(totalMilliseconds);
var hours = totalTime.getHours();
var minutes = totalTime.getMinutes();
var seconds = totalTime.getSeconds();