'How can I use localStorage to save this timer on page Refresh in angular 12?
How can I use localStorage to save this timer on page Refresh in angular 12 ?
timer:any;
ngOnInit(): void { this.startTimer() }
startTimer() {
this.timer = this.questions.length * 1 * 60;
let t = window.setInterval(() => {
if (this.timer <= 0) {
this.evaluateQuiz();
clearInterval(t);
} else {
this.timer--;
}
}, 1000); }
//using this in html
getFormattedTime() {
let mm = Math.floor(this.timer / 60);
let ss = this.timer - mm * 60;
return `${mm} min : ${ss} sec`; }
Solution 1:[1]
You cannot save whole interval. But what you can do is to save the remaining timer number (this.timer). You could set the localStorage.set('timer', this.timer) in the ngOnDestroy (which is called when the component gets destroyed). In the ngOnInit you would check if there is something in the cache and if so you would set it to this value. If you also need to reduce the value of the this.timer variable with the time between the last time you opened the page you need also to include the time when the component gets destroyed into the local storage.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | StyrianDev |
