RxJS - Time Observable
Fiddle exploring how to create and subscribe to an observable that wraps the setTimeout function in order to create
an observable timer object.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.js"></script>
<div id="target">
<p id="step"></p>
<p id="time">
subscribing ...
</p>
</div>
JavaScript
(function (undefined) {
"use strict";
class Timer {
constructor(fn, scope, args, ms) {
this._fn = fn;
this._scope = scope;
this._args = args;
this._ms = ms;
}
tick() {
let me = this;
return Rx.Observable.create(function (observer) {
let onTimeout = function () {
try{
let res = me._fn(me._scope, me._args || []);
observer.onNext(res);
observer.onCompleted();
} catch (err) {
observer.onError(err);
}
};
window.setTimeout(onTimeout, me._ms);
});
}
}
this.seconds = 0;
this.clock = new Timer(
function (self) {
return self.seconds += 1;
},
this, // scope
null, // arguments
1 // delay
);
this.tock = function () {
var me = this;
me.clock.tick().subscribe(
function onNext(res) {
let today = Date.now();
me.step = res;
d3.select("body")
.style("font-family", 'Courier, "Courier New"')
.style("text-align", 'center')
.style("background-color", '#0a001f')
.style("font-weight", '500')
.style("margin","0px")
.style("color", 'lime')
.style("vertical-align", "middle")
.style('font-size', function(d) {
let size = Math.ceil(30 * (window.innerWidth / window.innerHeight )) + 'px';
return size;
});
d3.select("p#time")
.text(today);
},
function onError(err) {
d3.select("p#target")
.append('div')
...