Hey first of all we declare our member functions a bit differently in typescript, so buttonClick should look like this
buttonClick() {
alert(this.timer);
this.timer = 0;
}
as mentioned in the comment by @Dai, getting systemtime at start (at ngOnInit) and subtracting that from the system time on click will require far fewer operations and be more accurate.
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);
}
EDIT: I edited the answer to show you have to use localStorage to persist values. This is similar to the answer above, however using idomatic typescript. I imagine the previous answer has lots of es5 experience and is resorting to those methods (nothing wrong with that). I find this style easier and clearer. I would reccomend taking an angular tutorial. Try the tour of heroes on their website and use Visual Studio code with Angular Essentials plugin as that will Lint and format your code properly so you can become accustomed to idiomatic typescript. Cheers.