How do Timer in Angular

Learn how to set your Angular code to fire after a set amount of time has passed

I had been working on a project where I need to refresh a page after a specific interval. For that, I had written a component that triggers an output event after a specified amount of time using @Input(). This is a higly customized component, as it is not doing anything active; rather, it owns the functionality and delegates the rest of the funcationality to the parent component that hosts this child component through @Input() and event emitters.

Coming straight to the code, I had used a time from RxJS to execute a code block after every second.

everySecond: Observable = timer(0, 1000);

this.subscription = this.everySecond.subscribe((seconds) => {
    var currentTime: moment.Moment = moment();
    this.remainingTime = this.searchEndDate.diff(currentTime)
    this.remainingTime = this.remainingTime / 1000;

    if (this.remainingTime <= 0) {
      this.SearchDate = moment();
      this.searchEndDate = this.SearchDate.add(this.ElapsTime, "minutes");

      this.TimerExpired.emit();
    }
    else {
      this.minutes = Math.floor(this.remainingTime / 60);
      this.seconds = Math.floor(this.remainingTime - this.minutes * 60);
    }
    this.ref.markForCheck()
})

This code describes itself. In this code, I used an Observable of type timer that fires after every 1000 ms. The subscription holds the refresh of the subscription to that timer firing event. Within the code block it looks for the remaining time to be greater than 0. If the remaining time is greater than 0, this component is cacluating minutes and seconds and storing them in the relevant variables, so that that can be shown on the front-end.

In case the remaining time is less than 0, it fires an output emitter that let’s the parent component know that the timer has elapsed and the business logic inside that parent component should execute.

On the last line of this component, this.ref.markForCheck() is asking the change detector whether the modal has changed and if the UI should be refreshed. This is only required if you have explicitly set ChangeDetectionStrategy or the component is going out of zone for any specific reason.

import { Component, OnInit, Output, Input, EventEmitter, ChangeDetectorRef } from '@angular/core';
import { Subscription, Observable, timer } from 'rxjs';
import * as moment from 'moment';

@Component({
selector: 'kt-auto-refresh',
templateUrl: './auto-refresh.component.html',
styleUrls: ['./auto-refresh.component.scss']
})
export class AutoRefreshComponent implements OnInit {

private subscription: Subscription;
@Output() TimerExpired: EventEmitter = new EventEmitter();

    @Input() SearchDate: moment.Moment = moment();
@Input() ElapsTime: number = 3;

searchEndDate: moment.Moment;
remainingTime: number;
minutes: number;
seconds: number;

everySecond: Observable = timer(0, 1000);

constructor(private ref: ChangeDetectorRef) {
this.searchEndDate = this.SearchDate.add(this.ElapsTime, "minutes");
}

ngOnInit() {
this.subscription = this.everySecond.subscribe((seconds) => {
var currentTime: moment.Moment = moment();
this.remainingTime = this.searchEndDate.diff(currentTime)
this.remainingTime = this.remainingTime / 1000;

if (this.remainingTime <= 0) {
this.SearchDate = moment();
this.searchEndDate = this.SearchDate.add(this.ElapsTime, "minutes");

this.TimerExpired.emit();
}
else {
this.minutes = Math.floor(this.remainingTime / 60);
this.seconds = Math.floor(this.remainingTime - this.minutes * 60);
        }
this.ref.markForCheck()
})
}

ngOnDestroy(): void {
this.subscription.unsubscribe();
}

}

Above is the full code of the timer component in TypeScript. Note that ElapseTime is set to 3 which means this component will fire the  timer elapse event after 3 minutes (by default). This is customizable from the parent component, and  I will proivde an example to use this component at the end of this article.

Also, when this component  is tried, it is automatically unscribed from the subscription event to avoid any memory leaks and those leaks are really crucial in these types of components.


	
		This page will refresh in {{minutes}}
 Min {{seconds}}
 Sec
	

Above is the HTML code that shows only the calculated minutes and seconds from the TypeScript code.

To use this component inside any other component we have to use the selector as shown in following example:

<kt-auto-refresh 
          (TimerExpired)="refresh()" 
          [hidden]="'true'">

By using the above snipped, the timer HTML will not be visible while it fires the refresh() event after 3 minutes.

<kt-auto-refresh 
          (TimerExpired)="refresh()" 
          [ElapsTime]="'10'" 
          [hidden]="'false'">

In this example, the timer component will fire the refresh event after 10 minutes and the HTML will be visible as well.

In case any one wanted to use this code snipped they can download it from following URL: https://gist.github.com/muhammadadilmalik/52fa872076cec56d7e3a773ede1f42d7

Thank for reading! If you enjoyed this article, please share it with others who may enjoy it as well.!

#angular #angular-js #web-development

How do Timer in Angular
3 Likes81.85 GEEK