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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • Why Angular Performance Problems Are Often Backend Problems
  • Faster Releases With DevOps: Java Microservices and Angular UI in CI/CD

Trending

  • Agentic Systems and Design Patterns
  • Building a Software Factory With AI Agents and Workflows
  • AI-Era Cybersecurity, Part 1: Mapping Glasswing, Daybreak, Lightwell and the Tools Racing to Find and Fix Bugs
  • AI Coding Agent Guardrails: Finding Gaps in Tool Permissions

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Updated May. 21, 19 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
111.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Zone-Free Angular: Unlocking High-Performance Change Detection With Signals and Modern Reactivity
  • When Angular APIs Return 200 but the Frontend Is Already Failing Users
  • Why Angular Performance Problems Are Often Backend Problems
  • Faster Releases With DevOps: Java Microservices and Angular UI in CI/CD

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook