Note: I understand that there is a timer observable from rxjs, but for the purpose of this project, I am using it as a proof of concept to enhance my understanding of observables.
In my Angular application, I have developed a timer with a start button, a display showing the elapsed seconds, and another display indicating the current state (stopped/executing/finished).
Upon clicking the start button, the example begins running, the state changes to "executing," and the seconds increment. However, when it reaches 5 seconds, it stops (displaying "finishing" in the log) without transitioning to "finished" (and the "finished" console log does not appear). Also, the error method is not triggered.
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-reloj',
templateUrl: './reloj.component.html',
styleUrls: ['./reloj.component.css']
})
export class RelojComponent implements OnInit {
public time: number = 0;
public state: string = "Stopped";
private crono = new Observable<number>(
observer => {
let start: number = (new Date()).getTime();
let lastCount = 0;
(function repeat() {
let now: number = (new Date()).getTime();
let seconds = ((now - start) / 1000 | 0);
if (lastCount < seconds) {
observer.next(seconds);
if (seconds >= 5) {
console.log("Finishing");
return;
}
lastCount = seconds;
}
setTimeout(
repeat,
100);
})();
});
constructor() { }
ngOnInit(): void {
}
onStart(): void {
console.log("Starting");
let self = this;
this.state = "Executing";
this.crono.subscribe({
next(seconds: number) {
console.log(`At next ${seconds}`);
self.time = seconds;
},
error(err) {
console.log("Error");
},
complete() {
console.log("Finished");
self.state = "Finished";
}
})
}
}
and the html
<button (click)="onStart()">Start</button>
<div>{{time}}</div>
<div>{{state}}</div>