Alternatively, if you do not want to live in a confusing timeout, you can write this completely as a stream:
// the stream const randomizer$ = Rx.Observable.of("") .switchMap(() => Rx.Observable .timer(getRandomDelay()) .mapTo(getRandomNumber())) .repeat(); // subscribe to it randomizer$.subscribe(num => console.log("Random number after random delay" + num)); // your utility functions function getRandomNumber() { return ~~(Math.random() * 200) } function getRandomDelay() { return Math.random() * 1000 }
A working example is here: http://jsbin.com/zipocaneya/edit?js,console
Alternative: First create a random number and then add a delay (if the runtime doesn't matter)
// the stream const randomizer$ = Rx.Observable.of("") .switchMap(() => Rx.Observable .of(getRandomNumber()) .delay(getRandomDelay() ) .repeat(); // subscribe to it randomizer$.subscribe(num => console.log("Random number after random delay" + num));
Note: Since a concurrency or async operation is performed off-stream, you can simply use concatMap or flatMap - in this case they all work the same way.
source share