Are you writing an app that needs to perform an action when you change text in an HTML input or textarea? If you want to throttle (debounce) changes until the user stops typing, rxjs has just what you need. In this example you learn how to use rxjs in the browser with plain ES6.

Use rxjs in the browser to throttle textbox changes.

In 2014 I wrote about throttling textbox changes in Wunderlist for the Windows 8 Store and recently needed the same thing for a javascript app that runs in the browser. This is what the example looks like:

throttle with rxjs

The first thing I found out is that importing the rx bits is not as easy as it is when using nodejs.

To use rxjs in the browser –using just ES6– you can use the import syntax if you decorate the script block with the type attribute set to module just like this:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="text" id="textbox" />
<div id="result"></div>
</body>
<script type="module">
import rxjs from 'https://dev.jspm.io/rxjs@6';
import operators from 'https://dev.jspm.io/rxjs@6/operators';
</script>
</html>

jspm

As you see, the scripts come from https://jspm.io/, which provides npm packages for the browser.

Throttle (or debouncing)

To throttle the textbox changes, you can use the fromEvent function to convert events (in this case the keyup-event) to an observable and then throttle the changes.

To chain rx functions in rxjs version 6, you need to pipe them like this:

rxjs
.fromEvent(document.getElementById("textbox"), 'keyup')
.pipe(
map(x => x.currentTarget.value),
debounceTime(500),
).subscribe(x => showResult(x));

Full example

Here is a complete example you can copy and paste in an empty html page:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="text" id="textbox" />
<div id="result"></div>
</body>
<script type="module">
import rxjs from 'https://dev.jspm.io/rxjs@6';
import operators from 'https://dev.jspm.io/rxjs@6/operators';
const { map, debounceTime } = operators;
const names = ["vera", "chuck", "dave", "paul", "ringo", "john", "george"];

rxjs
.fromEvent(document.getElementById("textbox"), 'keyup')
.pipe(
map(x => x.currentTarget.value),
debounceTime(500),
).subscribe(x => showResult(x));

function showResult(filter) {
let result = names
.filter(x => x.indexOf(filter) !== -1)
.join('<br />');
document.getElementById("result").innerHTML = result;
}
</script>
</html>

throttle with rxjs

Written by Loek van den Ouweland on 2019-03-17.
Questions regarding this artice? You can send them to the address below.