Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emit integers from certain range with some interval of time using rxjs

I'm using this but interval operator wants to be on observable object its not exist on range, is there a way to have observable that emit for example emit 60 integer with interval of 1 second, i have been doing this

 this.clock = Observable.range(1,60);
 this.clock = this.clock.interval(1000).map(function(value){
     console.log(value)
     return value;
 })

Its saying interval is not a function

also tried this:

 this.clock = Observable.range(1,60).interval(1000).map(function(value){
     console.log(value)
     return value;
 })
like image 659
blackHawk Avatar asked Nov 24 '16 09:11

blackHawk


1 Answers

To have a sequence from 1 to 60 with time interval of 1 second :

Observable
  .interval(1000)
  .map(x => x + 1) // to start from 1 instead of 0
  .map(x => console.log(x)) // do some logic here
  .take(60)
  .subscribe();

The output here is :

1
2
3
.
.
.
58
59
60

Here's a snippet that you can run to see the output :

// just to have the working demo on SO
let output = '';
let divToUpdate = document.getElementById('counter');

// observable
Rx.Observable
  .interval(1000)
  .map(x => x + 1) // to start from 1 instead of 0
  .map(x => {
    output = `${output}<br>${x}`;
    divToUpdate.innerHTML = output;
  })
  .take(60)
  .subscribe();
<div id="counter"></div>

<script src="https://npmcdn.com/[email protected]/bundles/Rx.umd.js"></script>
like image 146
maxime1992 Avatar answered Oct 20 '22 08:10

maxime1992