Building a Stopwatch

Let's see how to build a stopwatch in Rx and the categories of observables we require.

Stopwatch project

Enough theory, you’re probably itching to start building something. The first project you’ll take on in this course is a stopwatch that contains three observables. The stopwatch will have two buttons, one for starting and one for stopping, with an observable monitoring each.

Behind the scenes will be a third observable, ticking away the seconds since the start button was pressed in increments of 1/10th of a second. This observable will be hooked up to a counter on the page. You’ll learn how to create observables that take input from the user and observables that interact with the DOM to display the latest state of your app.

Working application

Below is the working application of our stopwatch built using observables. You will build these observables in the upcoming lessons.

Feel free to play with it.

Bud1
x.html
index.htmlIlocblob;(ÿÿÿÿÿÿpackage-lock.jsonIlocblob©(ÿÿÿÿÿÿpackage.jsonIlocblob(ÿÿÿÿÿÿpackage.json.sb-a48e3b48-LE4G1wIlocblob˜ÿÿÿÿÿÿstopwatch-complete.tsIlocblob…(ÿÿÿÿÿÿstopwatch.tsIlocblobó(ÿÿÿÿÿÿ
tsconfig.jsonIlocblob;˜ÿÿÿÿÿÿwebpack.config.jsIlocblob©˜ÿÿÿÿÿÿ @€ @€ @€ @E
DSDB `€ @€ @€ @
Stopwatch application project

How do we implement it?

Before we get to the code, take a second to think about how you’d implement this without Rx. There’d be a couple of click handlers for the start and stop buttons. At some point, the program would create an interval to count the seconds.

Sketch out the program structure:

  • What order do these events happen in?
  • Did you remember to clear the interval after the stop button was pressed?
  • Is business logic clearly separated from the view?

Typically, these aren’t concerns for an application of this size; I’m specifically calling them out now, so you can see how Rx handles them in a simple stopwatch. Later on, you’ll use the same techniques on much larger projects without losing clarity.

Categories of observables in stopwatch

This project has two different categories of observables:

  • The interval timer has its own internal state and outputs to the document object model (DOM).

  • The two-click streams will be attached to the buttons and won’t have any internal state.