3

How do I call a function in a set Time interval in Angular 2. I want it to be called/Triggered at specific time intervals(for eg 10 secs). For Eg: ts File

num: number = 0;
array: number[] = [1,5,2,4,7];
callFuntionAtIntervals(){
    if(num==5){
        num=0;    
    }
    num++;
}

HTML:

<div>{{ array[num] }}</div>

So basically the div value will change at intervals

Umair Khan
  • 195
  • 2
  • 4
  • 15
  • Use `Observable.interval`. –  Jun 20 '17 at 11:14
  • 1
    Possible duplicate of [How to call function every 2 mins in angular2?](https://stackoverflow.com/questions/36133430/how-to-call-function-every-2-mins-in-angular2) – Jota.Toledo Jun 20 '17 at 11:15
  • Possible duplicate of [Angular2 http at an interval](https://stackoverflow.com/questions/35316583/angular2-http-at-an-interval) – alex kucksdorf Jun 20 '17 at 11:17

4 Answers4

12

Observable.interval(10000).takeWhile(() => true).subscribe(() => this.function());

infinite loop where every each 10 seconds function() is being called

elzoy
  • 5,237
  • 11
  • 40
  • 65
  • 1
    What does the `takeWhile` accomplish here? –  Jun 20 '17 at 18:18
  • takeWhile() subscribes and mirrors the source Observable until the condition is satisfied. In simple words to break out of the interval, it is used. – Shubham Oct 04 '18 at 23:16
  • for eg :- You can initialize a boolean variable in class constructor as true, and then inside ngOnDestroy() you set that variable to false to come out of the interval. Hope this helps @user663031 – Shubham Oct 04 '18 at 23:22
  • 6
    error TS2339: Property 'interval' does not exist on type 'typeof Observable'. – Xb74Dkjb Mar 03 '19 at 05:00
  • Don't forget to unsubscribe it on `ngOnDestory()` – M Fuat Apr 08 '19 at 14:18
4

You may also try the traditional setInterval function.

setInterval(() => {
    this.callFuntionAtIntervals();
}, 1000);
SubbU
  • 349
  • 3
  • 6
3

In your TS logic, define an observable based on an "interval", which will emit the values 0, 1, 2, 3, 4, 0, 1, ...

this.index = Observable.interval(10000).map(n => n % this.array.length);

In your component, unwrap that observable using async and use it to index into the array.

{{array[index | async]}}
1

Please check below it might be some helpful,

My requirements: Like every 5 secs need to call a service if we get back required data we need to stop calling the service and continue with next flow. Else call service again after 5 seconds.

Conditions to stop service invocation were like after max number of retries (in my case 20 times) or after certain time (in my case 120 seconds).

Note: I was using in typescript

let maxTimeToRetry = 120000;  // in ms
let retryCount = 0;
let retryTimeout = 5000; // in ms
let maxRetries = 20;
const startTime = new Date().getTime();

// Need to use self inside of this, inside setInterval method;

const interval = setInterval(function () {
    retryCount++;  // INCREMENT RETRY COUNTER
    self.service.getData(requestParams).subscribe(result => {
      if (result.conditionTrue) {
        clearInterval(interval); // to stop the timer or to stop further calling of service
        //any execution after getting data
      }
    });

    if ((new Date().getTime() - startTime > maxTimeToRetry) || (retryCount === maxRetries)) {
      clearInterval(interval);
      // any execution 
    }

  }, retryTimeout);
Vishwa G
  • 573
  • 1
  • 6
  • 13