Cool123 Cool123 - 6 months ago 7
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>
<html>
<title>Tracking Time</title>
<style>
#time {
font-size: 250%
}
</style>
<center>
<body>
<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="https://code.jquery.com/jquery-2.1.0.js"></script>
<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)
</script>

</body>
</center>
</html>


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!

Answer

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();