Search⌘ K
AI Features

Running a Timer

Explore how to create a timer observable in RxJS that tracks elapsed time in tenths of a second and emits values periodically. Understand the concept of lazy observables, subscription behavior, and how to manage resource cleanup with unsubscribe functions to optimize performance.

Interval timer

Let’s tackle the interval timer behind the scenes that maintains the state.

This timer will need to track the total number of seconds elapsed and emit the latest value every 1/10th of a second. When the stop button is pressed, the interval should be canceled. We’ll need an observable for this, leading to the question: “How on earth do I build an observable?”

Run the code below and see what happens? Nothing appears in the console; the constructor never runs. Don’t worry about knowing everything that’s going on, but take a few guesses as you go through it. We will see later in this lesson, why that is so.

TypeScript 3.3.4
const { Observable} = require('rxjs');
let tenthSecond$ = new Observable(observer => {
let counter = 0;
observer.next(counter);
let interv = setInterval(() => {
counter++;
observer.next(counter);
}, 100);
return function unsubscribe() { clearInterval(interv); };
});

Explanation

Let’s walk through the code line-by-line.

  • Line 1, const { Observable} = require('rxjs'); is bringing in Observable from the RxJS library. All of the projects in this course ...