How do I call a function in every 10 seconds in An

2020-03-26 07:31发布

问题:

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

回答1:

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

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



回答2:

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]}}


回答3:

You may also try the traditional setInterval function.

setInterval(() => {
    this.callFuntionAtIntervals();
}, 1000);


回答4:

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);