Build a reactive countdown timer using RxJS and Angular
Tags: angular, tutorial, rxjs, frontend
Published: 2022-12-28 13:27:21

## Introduction

This is day 29 of Wes Bos's JavaScript 30 challenge and I am going to use RxJS and Angular to build a reactive countdown timer. The reactive countdown timer has the following functionalities:

- a button toolbar to start a timer that has 20 seconds, 5 minutes, 15 minutes, 30 minutes or 60 minutes interval
- A input field to enter arbitrary minutes
- Display time left
- Display the time when the timer stops

In this blog post, I describe how to merge button click and form submit streams to create a new stream to derive timer seconds. The new stream then emits the value to other streams to initiate count down and display timer stop time respectively. Ultimately, we build a reactive countdown timer that does not need a lot of codes to write.

### Create a new Angular project

```bash
ng generate application day29-countdown-timer
```

### Create Timer feature module

First, we create a Timer feature module and import it into AppModule. The feature module encapsulates TimerComponent, TimerControlsComponent and TimerPaneComponent.

### Import TimerModule in AppModule

``` typescript
// timer.module.ts

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TimerControlsComponent } from './timer-controls/timer-controls.component';
import { TimerPaneComponent } from './timer-pane/timer-pane.component';
import { TimerComponent } from './timer/timer.component';

@NgModule({
  declarations: [
    TimerComponent,
    TimerControlsComponent,
    TimerPaneComponent,
  ],
  imports: [
    CommonModule,
    FormsModule,
  ],
  exports: [
    TimerComponent
  ]
})
export class TimerModule { }

// app.module.ts

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    TimerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

### Declare Timer components in feature module

In Timer feature module, we declare three Angular components, TimerComponent, TimerControlsComponent and TimerPaneComponent to build a reactive countdown timer.

```bash
src/app
├── app.component.ts
├── app.module.ts
└── timer
    ├── index.ts
    ├── services
    │   └── timer.service.ts
    ├── timer
    │   └── timer.component.ts
    ├── timer-controls
    │   └── timer-controls.component.ts
    ├── timer-pane
    │   └── timer-pane.component.ts
    └── timer.module.ts
```

TimerComponent acts like a shell that encloses TimerControlsComponent and TimerPaneComponent. For your information, lt;app-timergt; is the tag of TimerComponent.

```typescript
// timer.component.ts

import { Component, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'app-timer',
  template: `
  <div class="timer">
    <app-timer-controls></app-timer-controls>
    <app-timer-pane></app-timer-pane>
  </div>
  `,
  styles: [` ...omitted due to brevity... `],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TimerComponent {}
```

TimerControlsComponent encapsulates buttons and input field to emit selected seconds whereas TimePaneComponent subscribes to the emitted value to initiate count down and render time left.

```typescript
// timer-controls.component.ts

import { ChangeDetectionStrategy, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { TimerService } from '../services/timer.service';

@Component({
  selector: 'app-timer-controls',
  template: `
  <div class="timer__controls">
    <button class="timer__button" #timer1>20 Secs</button>
    <button class="timer__button" #timer2>Work 5</button>
    <button class="timer__button" #timer3>Quick 15</button>
    <button class="timer__button" #timer4>Snack 20</button>
    <button class="timer__button" #timer5>Lunch Break</button>
    <form name="customForm" id="custom" #myForm="ngForm">
      <input type="text" name="minutes" placeholder="Enter Minutes" [(ngModel)]="customMinutes">
    </form>
  </div>`,
  styles: [` ...omitted due to brevity... `],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TimerControlsComponent implements OnInit, OnDestroy {

  @ViewChild('timer1', { static: true, read: ElementRef })
  timer1!: ElementRef<HTMLButtonElement>;

  @ViewChild('timer2', { static: true, read: ElementRef })
  timer2!: ElementRef<HTMLButtonElement>;

  @ViewChild('timer3', { static: true, read: ElementRef })
  timer3!: ElementRef<HTMLButtonElement>;

  @ViewChild('timer4', { static: true, read: ElementRef })
  timer4!: ElementRef<HTMLButtonElement>;

  @ViewChild('timer5', { static: true, read: ElementRef })
  timer5!: ElementRef<HTMLButtonElement>;

  @ViewChild('myForm', { static: true, read: ElementRef })
  myForm!: ElementRef<HTMLFormElement>;

  customMinutes = '';

  constructor(private timerService: TimerService) {}

  ngOnInit(): void {}

  ngOnDestroy(): void {}
}
```

```typescript
// timer-pane.component.ts

import { ChangeDetectionStrategy, Component } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { of } from 'rxjs';
import { TimerService } from '../services/timer.service';

@Component({
  selector: 'app-timer-pane',
  template: `
    <div class="display">
      <h1 class="display__time-left">{{ displayTimeLeft$ | async }}</h1>
      <p class="display__end-time">{{ displayEndTime$ | async }}</p>
    </div>`,
  styles: [` ...omitted due to brevity ...`],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TimerPaneComponent {

  oneSecond = 1000;
  
  displayEndTime$ = of('');

  displayTimeLeft$ = of('');

  constructor(private titleService: Title, private timerService: TimerService) {}
}
```

Next, I delete boilerplate codes in AppComponent and render TimerComponent in inline template.

```typescript
import { Component } from '@angular/core';
import { Title } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  template: '<app-timer></app-timer>',
  styles: [`
    :host {
      display: block;
    }
  `]
})
export class AppComponent {
  title = 'Day 29 Countdown Timer';

  constructor(titleService: Title) {
    titleService.setTitle(this.title);
  }
}
```

### Add timer service to share RxJS subjects and observables

In order to communicate data between TimerControlsComponent and TimerPaneComponent, I implement a TimerService to store Subjects and Observables that the components subscribe to stream events.

```typescript
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class TimerService {

  private readonly secondsSub = new Subject<number>(); 
  readonly seconds$ = this.secondsSub.asObservable();

  updateSeconds(seconds: number) {
    this.secondsSub.next(seconds);
  }
}
```

### Use RxJS and Angular to implement timer control components

I am going to define Observables for button click and form submit events. Then, merge these observables to create a new observable to emit the selected seconds

Use `ViewChild` to obtain references to buttons and template-driven form

```typescript
 @ViewChild('timer1', { static: true, read: ElementRef })
 timer1!: ElementRef<HTMLButtonElement>;

 @ViewChild('timer2', { static: true, read: ElementRef })
 timer2!: ElementRef<HTMLButtonElement>;

 @ViewChild('timer3', { static: true, read: ElementRef })
 timer3!: ElementRef<HTMLButtonElement>;

 @ViewChild('timer4', { static: true, read: ElementRef })
 timer4!: ElementRef<HTMLButtonElement>;

 @ViewChild('timer5', { static: true, read: ElementRef })
 timer5!: ElementRef<HTMLButtonElement>;

 @ViewChild('myForm', { static: true, read: ElementRef })
 myForm!: ElementRef<HTMLFormElement>;
```
Declare subscription instance member and unsubscribe in 
ngDestroy()

```typescript
subscription = new Subscription();

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

Create observables and emit value to secondsSub subject and subscribe in ngOnInit().

```typescript
ngOnInit(): void {
    const videoNativeElement = this.video.nativeElement;
    const timer1$ = this.createButtonObservable(this.timer1.nativeElement, 20);
    const timer2$ = this.createButtonObservable(this.timer2.nativeElement, 300);
    const timer3$ = this.createButtonObservable(this.timer3.nativeElement, 900);
    const timer4$ = this.createButtonObservable(this.timer4.nativeElement, 1200);
    const timer5$ = this.createButtonObservable(this.timer5.nativeElement, 3600);

    const myForm$ = fromEvent(this.myForm.nativeElement, 'submit')
      .pipe(
        filter(() => !!this.customMinutes),
        map(() => parseFloat(this.customMinutes)),
        map((customMinutes) => Math.floor(customMinutes * 60)),
        tap(() => this.myForm.nativeElement.reset())
      );

    this.subscriptions.add(
      merge(timer1$, timer2$, timer3$, timer4$, timer5$, myForm$)
        .subscribe((seconds) => this.timerService.updateSeconds(seconds))
    );
}

createButtonObservable(nativeElement: HTMLButtonElement, seconds: number) {
   return fromEvent(nativeElement, 'click').pipe(map(() => seconds))
}
```

`myForm$` involves several steps in order to emit inputted seconds

- filter(() => !!this.customMinutes) does nothing until input field has value
- map(() => parseFloat(this.customMinutes)) converts value from string to number
- map((customMinutes) => Math.floor(customMinutes * 60)) converts minutes to seconds
- tap(() => this.myForm.nativeElement.reset()) resets template-driven form

### Implement count down in TimerPaneComponent reactively

```typescript
// timer-pane.component.ts

constructor(private titleService: Title, private timerService: TimerService) { }
  
oneSecond = 1000;
nowTo$ = this.timerService.seconds$.pipe(shareReplay(1));

countDown$ = this.nowTo$.pipe(
    switchMap((seconds) => timer(0, this.oneSecond).pipe(take(seconds + 1)))
);
displayTimeLeft$ = this.countDown$
   .pipe(
       withLatestFrom(this.nowTo$),
       map(([countdown, secondsLeft]) => secondsLeft - countdown),
       map((secondsLeft) => this.displayTimeLeft(secondsLeft)),
       tap((strTimeLeft) => this.titleService.setTitle(strTimeLeft))
    );

private displayTimeLeft(seconds: number) {
    const minutes = Math.floor(seconds / 60);
    const remainderSeconds = seconds % 60;
    return `${minutes}:${remainderSeconds < 10 ? '0' : '' }${remainderSeconds}`;
}
```

`nowTo$` is an observable that emits the selected seconds. When I provide the selected seconds (let’s say N), I have to cancel the previous timer and create a new timer that emits (N + 1) values (0, 1, 2, ….N). Therefore, I use `switchMap` to return a timer observable

When `countDown$` emits a value, one second has elapsed and time left also decrements by 1 second

- withLatestFrom(this.nowTo$) obtains the selected seconds
- map(([countdown, secondsLeft]) => secondsLeft – countdown) derives the remaining seconds
- map((secondsLeft) => this.displayTimeLeft(secondsLeft)) displays the remaining seconds in mm:ss format
- tap((strTimeLeft) => this.titleService.setTitle(strTimeLeft)) updates the document title to display the remaining time

Therefore, `displayTimeLeft$` is responsible for emitting the remaining time in mm:ss format.

### Display timer end time reactively

```typescript
// timer-pane.component.ts

displayEndTime$ = this.nowTo$.pipe(map((seconds) => this.displayEndTime(Date.now(), seconds)));

private displayEndTime(now: number, seconds: number): string {
    const timestamp = now + seconds * this.oneSecond;

    const end = new Date(timestamp);
    const hour = end.getHours();
    const amPm = hour >= 12 ? 'PM': 'AM';
    const adjustedHour = hour > 12 ? hour - 12 : hour;
    const minutes = end.getMinutes();
    return `Be Back At ${adjustedHour}:${minutes < 10 ? '0' : ''}${minutes} ${amPm}`;
 }
```

`displayEndTime$` is a trivial observable. It adds seconds to the current time to obtain the end time of the timer. Then, the Date object is formatted to hh:mm:ss AM/PM. Next, the observable is resolved in the inline template by async pipe.

The example is done and we have built a reactive countdown timer successfully.

## Final Thoughts

In this post, I show how to use RxJS and Angular to build a reactive countdown timer. The first takeaway is to use switchMap and timer to create an observable to emit an integer per second to mimic count down. I achieve the effect declaratively without implementing any complex logic. The second takeaway is to encapsulate subject and observable in a shared service to exchange data between sibling components. The final takeaway is to use async pipe to resolve observable such that developers do not have to clean up subscriptions.

This is the end of the blog post and I hope you like the content and continue to follow my learning experience in Angular and other technologies.

## Resources:
- Repo: https://github.com/railsstudent/ng-rxjs-30/tree/main/projects/day29-countdown-timer
- Live demo: https://railsstudent.github.io/ng-rxjs-30/day29-countdown-timer/
- Wes Bos's JavaScript 30 Challenge: https://github.com/wesbos/JavaScript30