In Addition to all the previous answers, I would do it using RxJS Observables
please check Observable.timer
Here is a sample code, will start after 2 seconds and then ticks 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 on the AppComponent class, you can do one of the following:
** Assuming the function you want to call is named 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 subscriber object instead of the AppComponent object which is probably not what you want.
However, in the below approach, you create a lambda expression and call the function func inside it. This way, the call to func is still inside the scope of AppComponent. This is the best way to do it in my opinion.
ngOnInit(){
let timer = Observable.timer(2000,1000);
timer.subscribe(t=> {
this.func(t);
});
}
check this plunker for working code.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…