+ 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)

27th Dec 2021, 7:58 PM
Priyangshu
Priyangshu - avatar
6 Respuestas
+ 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
27th Dec 2021, 8:29 PM
VCoder
VCoder - avatar
+ 5
VCoder Thank you for the help. The code is working perfectly now
27th Dec 2021, 9:04 PM
Priyangshu
Priyangshu - avatar
+ 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;
27th Dec 2021, 8:20 PM
VCoder
VCoder - avatar
+ 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
27th Dec 2021, 8:25 PM
Priyangshu
Priyangshu - avatar
0
When you say the "time", you mean here "t" of localStorage, right ?
27th Dec 2021, 8:09 PM
VCoder
VCoder - avatar
0
time is used to display the time
28th Dec 2021, 3:26 AM
Shubham Bhatia
Shubham Bhatia - avatar