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.
Abdulrahman Mar 05 '16 at 11:30 2016-03-05 11:30
source share