Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 615
Bogdan Pușcașu Avatar asked Apr 30 '18 08:04

Bogdan Pușcașu


People also ask

What is $interval in AngularJS?

AngularJS's wrapper for window. setInterval . The fn function is executed every delay milliseconds. The return value of registering an interval function is a promise. This promise will be notified upon each tick of the interval, and will be resolved after count iterations, or run indefinitely if count is not defined.

What are $Location $timeout and interval?

$interval executes a callback repeatedly, while $timeout simply delays the execution of a callback (doesn't repeat). So, no, they're not the same. Additionally, it should be noted that both of them are wrappers for window.


2 Answers

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.

like image 64
siva636 Avatar answered Sep 17 '22 05:09

siva636


You can use interval from rxjs

import { interval } from 'rxjs/observable/interval';

//emit value in sequence every 1 second
const source = interval(1000);
//output: 0,1,2,3,4,5....
const subscribe = source.subscribe(val => console.log(val));

This will emit new value after every 1 second

like image 37
ashfaq.p Avatar answered Sep 19 '22 05:09

ashfaq.p