First and foremost, it's important to note that we define our member functions differently in TypeScript. Therefore, the buttonClick function should be written as follows:
buttonClick() {
alert(this.timer);
this.timer = 0;
}
As suggested by @Dai, a more efficient and accurate approach would be to get the system time at initialization (ngOnInit) and calculate the difference from the system time on click.
ngOnInit() {
this.startTime = localStorage.startTime ? JSON.parse(localStorage.startTime) : (new Date().getTime());
localStorage.setItem('startTime', JSON.stringify(this.startTime));
}
buttonClick() {
this.startTime = JSON.parse(localStorage.startTime);
alert((this.startTime - (new Date().getTime())) / 1000);
}
UPDATE: I have revised the answer to demonstrate how to utilize localStorage for persisting values. While similar to the previous solution, this approach employs idiomatic TypeScript practices. For those accustomed to ES5 methods, there is no issue with using them; however, I find this style to be clearer and easier to understand. To enhance your TypeScript skills, consider going through an Angular tutorial such as the "Tour of Heroes" on the official website. Additionally, using Visual Studio Code with the Angular Essentials plugin can help format and lint your code correctly. This will assist you in familiarizing yourself with idiomatic TypeScript coding. Best of luck!