Search code examples
angularrxjsobservabledelayrepeat

Angular 5 - equivalent to $interval from AngularJS


I'm trying to find the equivalent of the $interval from AngularJS into Angular 5.

$interval will repeat a function call or a block a specified number of times with a delay in-between. This is what I would like to do, written in AngularJS:

$interval(function() {
      myFunction(param1, param2)
      i++;
    }, delay, count);

Make abstraction of i, I'm using it for a different purpose. How can this be achieved in Angular 5? I already tried using rxjs/Observable but I can't seem to find a way to include both the delay and the run multiple times part.

Thank you.


Solution

  • You may make use of the timer static method and take operator.

    import {timer} from 'rxjs';
    import {take} from 'rxjs/operators';  
    
    timer(yourDelay, 1000).pipe(
       take(yourCount)).subscribe(x=>{
        // do here whatever you want to do here
        })
    

    I assumed you use RxJS 6.