Currently, I am learning Angular and have come across a particular issue. As far as I understand, everything placed within the `ngOnInit` method gets executed every time the component reloads. I have a timer function that needs to continue running even after the page is reloaded, without resetting the count. Is there a way to execute the `startTimer(secsToStart: number)` function outside of `ngOnInit`, in the HTML file, or should I explore other Angular features for this purpose?
Here is the code snippet for the component:
@Component({
selector: 'app-task-countdown',
templateUrl: './task-countdown.component.html',
styleUrls: ['./task-countdown.component.css'],
})
export class TaskCountdownComponent implements OnInit {
@Input()
tasks!: Tasks[];
excuse!: Loosers[];
excuseForm!: FormGroup;
expirationCounter!: string;
timeIsUp = false;
donePushed = false;
constructor(
private fb: FormBuilder,
private tasksService: TasksService,
private excuseService: ExcuseService,
private router: Router
) {}
ngOnInit() {
this.tasks = this.tasksService.getTasks();
this.startTimer(86400);
this.excuseForm = this.fb.group({
excuse: '',
});
this.excuseForm.valueChanges.subscribe(console.log);
}
addExcuse() {
const excuseValue = this.excuseForm.value;
this.excuseService.addExcuse(excuseValue);
this.router.navigate(['/loosers']);
}
onTaskDone() {
this.donePushed = true;
}
startTimer(secsToStart: number): void {
var start: number = secsToStart;
var h: number;
var m: number;
var s: number;
var temp: number;
var timer: any = setInterval(() => {
h = Math.floor(start / 60 / 60);
temp = start - h * 60 * 60;
m = Math.floor(temp / 60);
temp = temp - m * 60;
s = temp;
var hour = h < 10 ? '0' + h : h;
var minute = m < 10 ? '0' + m : m;
var second = s < 10 ? '0' + s : s;
this.expirationCounter = hour + ':' + minute + ':' + second;
if (start <= 0) {
clearInterval(timer);
this.expirationCounter = 'Expired';
this.timeIsUp = true;
this.tasks = [];
} else if (this.donePushed) {
clearInterval(timer);
console.log(start);
}
start--;
}, 1000);
}
}
In the HTML section, the timer runs and displays `expirationCounter` value inside a span element:
<app-nav-bar></app-nav-bar>
<div *ngFor="let tasks of tasks">
<p>{{ tasks.task }}</p>
<button (click)="onTaskDone()">Done</button>
</div>
<div>
<span id="myTimeCounter">{{ expirationCounter }}</span>
</div>
<div *ngIf="this.timeIsUp">
<form [formGroup]="excuseForm">
<input
type="text"
placeholder="write down your excuses .. "
formControlName="excuse"
/>
<button (click)="addExcuse()">Add</button>
</form>
</div>