+ 4
Why does the time turn 0 everytime I run the code?
var time = 0; setInterval(function() { time++ localStorage.setItem("t", time); document.getElementById("a").innerHTML = localStorage.getItem("t"); }, 1000)
6 Réponses
+ 3
let time = localStorage.getItem("t") || 0; // check if "t" exists in localStorage, if true, assign the value to time, else assign 0 to it
+ 5
VCoder Thank you for the help. The code is working perfectly now
+ 2
Simply because properties in the localStorage will remain permanently and when you run the code, you set "t" to time which is equel to 0 at the starting of the code, to fix this, just replace the time variable definition by this : let time = localStorage.getItem("t") || 0;
+ 2
VCoder what should I do so that the time doesn't restart to 0 and instead start from where it was when I close the browser
0
When you say the "time", you mean here "t" of localStorage, right ?
0
time is used to display the time