How do I call a function in every 10 seconds in Angular 2?

前端 未结 4 1988
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 11:23

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

nu         


        
相关标签:
4条回答
  • 2021-01-14 11:52

    You may also try the traditional setInterval function.

    setInterval(() => {
        this.callFuntionAtIntervals();
    }, 1000);
    
    0 讨论(0)
  • 2021-01-14 11:52

    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);
    
    0 讨论(0)
  • 2021-01-14 12:00

    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]}}
    
    0 讨论(0)
  • 2021-01-14 12:05

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

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

    0 讨论(0)
提交回复
热议问题