Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 run a function in every X seconds

People also ask

How do you run a function every 5 seconds in TypeScript?

Use the setInterval() method to call a function every N seconds in TypeScript, e.g. setInterval(myFunction, seconds * 1000) . The first parameter the method takes is the function that will be called on a timer, and the second parameter is the delay in milliseconds. Copied!

What is interval in angular?

AngularJS includes $interval service which performs the same task as setInterval() method in JavaScript. The $interval is a wrapper for setInterval() method, so that it will be easy to override, remove or mocked for testing. The $interval service executes the specified function on every specified milliseconds duration.


Use interval from rxjs

Here's how:

import { interval, Subscription } from 'rxjs';

subscription: Subscription;

...

//emit value in sequence every 10 second
const source = interval(10000);
const text = 'Your Text Here';
this.subscription = source.subscribe(val => this.opensnack(text));

...

ngOnDestroy() {
  this.subscription.unsubscribe();
}

Alternatively, you can use setInterval which is available as method on the Window Object. So you don't need to import anything to use it.

intervalId = setInterval(this.opensnack(text), 10000);

...

ngOnDestroy() {
  clearInterval(this.intervalId);
}

Here's a SAMPLE STACKBLITZ for your ref.


You can make use of rxjs library to run a function every X seconds.

import { interval } from 'rxjs';
import { takeWhile } from 'rxjs/operators';

...

 interval(1000)
    .pipe(takeWhile(() => !stop))
    .subscribe(() => {
      // place you code here
    });

The above code snippet will execute the subscribed statements every 1 second, until the stop condition is set to true.


Try to use setInterval

setInterval will allow to run a function regularly with the interval between the runs

https://javascript.info/settimeout-setinterval

Example:

function opensnack(text: string) : void {
  console.log(text);
}

setInterval(opensnack, 10000, "my text"); <-- run every 10 second

You can look at this stackblitz example:


Angular 6 run a function in every X seconds

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';

@Component({
    selector: 'my-app',
    template: `<h2>
      Now {{time | date: 'hh:mm:ss'}}
      
      <hr /> 
      Now {{time$ | async | date: 'hh:mm:ss'}}
    </h2>`
})
export class AppComponent {
  time: Date;
  time$;

  constructor() {
    // First way: manual subscribe
    Observable
      .interval(1000)
      .map(() => new Date())
      .subscribe(res => this.time = res)

    // Angular way: by using the `async` pipe
    this.time$ = Observable.interval(1000).map(() => new Date())
  }
}