RxJS Time Interval
Shows that a calculation can vary dynamically as a function of an observable time interval.
by Lou Mauget
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.js"></script>
<h4>RxJS Time Interval Observable</h4>
<p>
Distance at <span id="mph">0</span> mph for <span id="hours">0</span> hours is
<span id="miles">0</span> miles.
</p>
CSS
body {
font-family: sans-serif
}
span {
color: #0000ff;
font-weight: 800;
}
JavaScript
// distance = rate * time
var R = 60; // mph
var t = 0; // We'll step up at intervals
var source = Rx.Observable
.interval(500) // 1 second interval
.skip(1) // Skip zeroth
.take(10); // Take next 10
// Kick off ...
source.subscribe(
function( t ) {
console.log('hours: ' + t);
$('#mph').html(R);
$('#hours').html(t);
$('#miles').html(R * t); // Do the math, display it
},
function(err) { console.log('Error: ' + err)},
function() { console.log('Completed')} );