Implement a Countdown Timer with RxJS in Angular

Implement a simple countdown in Angular

Photo by Eder Pozo Pérez on Unsplash

Counting down to some special event is something we do a lot.

In this guide, I will show you how to implement a simple and effective countdown timer in Angular using RxJS.

So far, 2020 has been a roller coaster year. How about we implement a countdown timer to the year 2021? The countdown timer we will implement will be updated to the second.

Without further ado, let's jump into the code.

Create an Angular application

We will get started by creating a simple Angular application via the CLI with the following command.

$ ng new count-down-timer --defaults

Once the application is created go into its root directory.

$ cd count-down-timer

Then add a new component named count-down which will contain the logic for our countdown timer using the following CLI command.

ng g c count-down

At this stage, your project structure should be similar to this.

image

Implementing the countdown logic

The logic for the countdown time is not complicated. We need to find the difference between the D-day i.e., the day of our event and the current time.

The difference in the time we get is in Milliseconds, so we will convert it into corresponding units i.e., days, hours, minutes, and seconds.

To make sure that the time keeps updating every second, we will use subscription interval which will get the difference in time every second.

To avoid memory leaks in the application, we will unsubscribe from the subscription whenever the count-down component is being destroyed.

The component code should look as below. I have gone for readability over efficiency, so feel free to make modifications if you wish to.

I will not go into detail regarding the time difference calculations in this article, however, I have provided a link to an article regarding the same in the conclusion section.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription, interval } from 'rxjs';

@Component({
  selector: 'app-count-down',
  templateUrl: './count-down.component.html',
  styleUrls: ['./count-down.component.css']
})
export class CountDownComponent implements OnInit, OnDestroy {

    private subscription: Subscription;

    public dateNow = new Date();
    public dDay = new Date('Jan 01 2021 00:00:00');
    milliSecondsInASecond = 1000;
    hoursInADay = 24;
    minutesInAnHour = 60;
    SecondsInAMinute  = 60;

    public timeDifference;
    public secondsToDday;
    public minutesToDday;
    public hoursToDday;
    public daysToDday;


    private getTimeDifference () {
        this.timeDifference = this.dDay.getTime() - new  Date().getTime();
        this.allocateTimeUnits(this.timeDifference);
    }

  private allocateTimeUnits (timeDifference) {
        this.secondsToDday = Math.floor((timeDifference) / (this.milliSecondsInASecond) % this.SecondsInAMinute);
        this.minutesToDday = Math.floor((timeDifference) / (this.milliSecondsInASecond * this.minutesInAnHour) % this.SecondsInAMinute);
        this.hoursToDday = Math.floor((timeDifference) / (this.milliSecondsInASecond * this.minutesInAnHour * this.SecondsInAMinute) % this.hoursInADay);
        this.daysToDday = Math.floor((timeDifference) / (this.milliSecondsInASecond * this.minutesInAnHour * this.SecondsInAMinute * this.hoursInADay));
  }

    ngOnInit() {
       this.subscription = interval(1000)
           .subscribe(x => { this.getTimeDifference(); });
    }

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

}

In the corresponding template code, i.e count-down.component.html, we will display the time to our D-day in respective units using interpolation as follows.

<div class="timer">
  <h4>Count down timer</h4>
  <span id="days"> {{daysToDday}} </span>Day(s)
  <span id="hours"> {{hoursToDday}} </span>Hrs
  <span id="minutes"> {{minutesToDday}} </span>Min
  <span id="seconds"> {{secondsToDday}} </span>S
</div>

Add some CSS styling to the component's style template as follows. The styling will center our output and adjust font size.

.timer {
  text-align: center;
  font-family: Arial, sans-serif;
  font-size: 1.4em;
  letter-spacing: -1px;
}
.timer span {
  font-size: 2em;
  margin: 0 3px 0 15px;
}

The CSS is pretty basic, to keep things simple. Feel free to tweak it.

Displaying the timer

To display the time remaining to the D-day, we will inject the count-down child component into the app.component.html parent component as below.

Remove all the code in the app.component.html and replace it with the following single line of code.

<app-count-down> </app-count-down>

The countdown timer in action

To serve the application in your default browser, you can run the following command.

ng serve -o

Here is a look at the countdown timer in action.

image

Conclusion

There you have it, a simple implementation of a countdown timer updated to the second.

For a comprehensive guide on calculating time differences in JavaScript, you can take look a guide by the Javascript Jeep🚙💨 here.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics