DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Rediscovering Angular: Modern Advantages and Technical Stack
  • Angular Input/Output Signals: The New Component Communication
  • Azure Deployment Using FileZilla
  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators

Trending

  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • The Modern Data Stack Is Overrated — Here’s What Works
  • What Is Plagiarism? How to Avoid It and Cite Sources
  1. DZone
  2. Coding
  3. Frameworks
  4. Angular Timer (Auto Refresh Component)

Angular Timer (Auto Refresh Component)

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

By 
Muhammad Adil Malik user avatar
Muhammad Adil Malik
·
Updated May. 21, 19 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
109.9K Views

Join the DZone community and get the full member experience.

Join For Free

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<number> = 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<any> = new EventEmitter<any>();

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

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

everySecond: Observable<number> = 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.

<div class="row" style="margin-bottom: 12px;" [hidden]="hidden">
	<div class="col-md-12" style="text-align: center;">
		This page will refresh in <div class="time">{{minutes}}</div> Min <div class="time">{{seconds}}</div> Sec
	</div>
</div>

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'">
</kt-auto-refresh>

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'">
</kt-auto-refresh>

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

AngularJS

Published at DZone with permission of Muhammad Adil Malik. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Rediscovering Angular: Modern Advantages and Technical Stack
  • Angular Input/Output Signals: The New Component Communication
  • Azure Deployment Using FileZilla
  • Angular RxJS Unleashed: Supercharge Your App With Reactive Operators

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!