In a previous post, I created a sample app to demonstrate switchMap operator. In this post, I will build on that example and use it to demonstrate takeUntil operator in order to implement the stop functionality of the start interval.

To begin with, create a stop <button> with a label of Stop and create a new query selector for the button.

const stopButton = document.querySelector('#stop');

To stop the interval initialized from the start I will show what I did. I’ll do it the wrong way so I can show what not to do as this is a common mistake I’ve seen.


const subscription = interval$
	.subscribe((x) => console.log(x));

Observable.fromEvent(stopButton, 'click')
	.subscribe(() =>{


What I’m doing is saving the subscription interval$.subscribe() returns

And then using it to unsubscribe once the stop button is clicked.

This will work as I said this is wrong it shouldn’t be done this way.

Instead of getting references to subscriptions, we should have streams work together. We want an interval$ that goes until a stopButton interval$ fires.

The correct way of doing this will look something like this:

	.takeUntil(Observable.fromEvent(stopButton, 'click'))
	.subscribe((x) => console.log(x));

which reads as : run this interval$ until (.takeUntil() operator) the other observable (Observable.fromEvent(stopButton, ‘click’)) gets clicked.

This will work and will be fine but we can improve its look so it’s easier to read and maintain.

const stop$ = Observable.fromEvent(stopButton, 'click');

const intervalThatStops$ = interval$

intervalThatStops$.subscribe((x)=> console.log(x));

and finally all together will looks like this:

const start$ = Observable.fromEvent(startButton, 'click');

const stop$ = Observable.fromEvent(stopButton, 'click');

const intervalThatStops$ = interval$

const startInterval$ = start$
	.subscribe((x)=> console.log(x));
[vc_custom_heading text=”” link=”|title:Code||”]


Please enter your comment!
Please enter your name here