How to create a timer in angular2

I need a timer in Angular 2, which ticks after a certain period of time and performs some tasks (maybe calling some functions).

How to do this with Angular 2?

+89
javascript angular
Mar 05 '16 at 11:06
source share
9 answers

In addition to all the previous answers, I would do this with RxJS Observables

please check Observable.timer

Here is an example code that starts in 2 seconds and then marks every second:

import {Component} from 'angular2/core'; import {Observable} from 'rxjs/Rx'; @Component({ selector: 'my-app', template: 'Ticks (every second) : {{ticks}}' }) export class AppComponent { ticks =0; ngOnInit(){ let timer = Observable.timer(2000,1000); timer.subscribe(t=>this.ticks = t); } } 

And here is a working plunker

Update If you want to call a function declared in the AppComponent class, you can do one of the following:

** Assuming the function you want to call is called func ,

 ngOnInit(){ let timer = Observable.timer(2000,1000); timer.subscribe(this.func); } 

The problem with the above approach is that if you call 'this' inside func, it will refer to the subscribing object instead of the AppComponent object, which is probably not the one you want.

However, in the approach below, you create a lambda expression and call the func function on it. So the func function call is still in the scope of the AppComponent. This is the best way to do this, in my opinion.

 ngOnInit(){ let timer = Observable.timer(2000,1000); timer.subscribe(t=> { this.func(t); }); } 

check this plunker for working code.

+127
Mar 05 '16 at 11:30
source share

Another solution is to use TimerObservable

TimerObservable is a subclass of Observable.

 import {Component, OnInit, OnDestroy} from '@angular/core'; import {Subscription} from "rxjs"; import {TimerObservable} from "rxjs/observable/TimerObservable"; @Component({ selector: 'app-component', template: '{{tick}}', }) export class Component implements OnInit, OnDestroy { private tick: string; private subscription: Subscription; constructor() { } ngOnInit() { let timer = TimerObservable.create(2000, 1000); this.subscription = timer.subscribe(t => { this.tick = t; }); } ngOnDestroy() { this.subscription.unsubscribe(); } } 

PS: Do not forget to unsubscribe.

+77
Sep 23 '16 at 15:46
source share
 import {Component, View, OnInit, OnDestroy} from "angular2/core"; import { Observable, Subscription } from 'rxjs/Rx'; @Component({ }) export class NewContactComponent implements OnInit, OnDestroy { ticks = 0; private timer; // Subscription object private sub: Subscription; ngOnInit() { this.timer = Observable.timer(2000,5000); // subscribing to a observable returns a subscription object this.sub = this.timer.subscribe(t => this.tickerFunc(t)); } tickerFunc(tick){ console.log(this); this.ticks = tick } ngOnDestroy(){ console.log("Destroy timer"); // unsubscribe here this.sub.unsubscribe(); } } 
+11
May 11 '17 at 7:09 a.m. a.m.
source share

In rxjs 6.2.2 and Angular 6.1.7, I got the error "Observable.timer is not function".

This was resolved by replacing "Observable.timer" with "timer":

 import { timer, Subscription } from 'rxjs'; private myTimerSub: Subscription; ngOnInit(){ const ti = timer(2000,1000); this.myTimerSub = ti.subscribe(t => { console.log("Tick"); }); } ngOnDestroy() { this.myTimerSub.unsubscribe(); } 
+4
Sep 29 '18 at 16:07
source share

I had a problem with the fact that I had to use a timer, but I had to display them in 2 components at the same time, on one screen. I created timerObservable in the service. I signed up for a timer in both components, and what happened? It will not be synchronized because a new subscription always creates its own stream.

I would like to say that if you plan to use one timer in several places, always put .publishReplay(1).refCount() at the end of the Observer, because it will publish the same stream from it every time.

Example:

 this.startDateTimer = Observable.combineLatest(this.timer, this.startDate$, (localTimer, startDate) => { return this.calculateTime(startDate); }).publishReplay(1).refCount(); 
+3
Apr 29 '17 at 8:54 on
source share

You can simply use the setInterval utility and use the arrow function as a callback to have this point to an instance of the component.

For example:

 this.interval = setInterval( () => { // call your functions like this.getList(); this.updateInfo(); }); 

Inside your ngOnDestroy lifecycle hook, clear the interval.

 ngOnDestroy(){ clearInterval(this.interval); } 
+3
Feb 14 '18 at 12:35
source share

An npm package was found that simplifies working with RxJS as a service.

https://www.npmjs.com/package/ng2-simple-timer

You can "subscribe" to an existing timer so that you do not create bazillion timers if you use it many times in the same component.

+1
Jun 20 '17 at 20:27
source share

If you want to run a method in ngOnInit, you can do something like this:

import these 2 libraries from RXJS:

 import {Observable} from 'rxjs/Rx'; import {Subscription} from "rxjs"; 

Then declare a timer and a private subscription, for example:

 timer= Observable.timer(1000,1000); // 1 second for 2 seconds (2000,1000) etc private subscription: Subscription; 

Last but not least important method of starting when the timer stops

 ngOnInit() { this.subscription = this.timer.subscribe(ticks=> { this.populatecombobox(); //example calling a method that populates a combobox this.subscription.unsubscribe(); //you need to unsubscribe or it will run infinite times }); } 

That's it, Angular 5

+1
Apr 18 '18 at 15:44
source share
 Set Timer and auto call service after certain time // Initialize from ngInit ngOnInit(): void {this.getNotifications();} getNotifications() { setInterval(() => {this.getNewNotifications(); }, 60000); // 60000 milliseconds interval } getNewNotifications() { this.notifyService.getNewNotifications().subscribe( data => { // call back }, error => { }, ); } 
0
Jan 09 '19 at 11:08
source share



All Articles