I would like to run a function in every 1 second. After searching, I found setInterval
but it doesn't work for me.
setInterval(function(){
this.myfuntion();
}, 1000);
I also tried this.myfuntion
but it doesn't work too.
The solution is to use Arrow functions:
setInterval(() => {
this.myfuntion(); // Now the "this" still references the component
}, 1000);
When using arrow functions, the this
property is not overwritten and still references the component instance.
There are Basically two methods to perform that.
Try using observable which will suit best your requirement.
Method 1:
import {Observable} from 'Rxjs/rx';
import { Subscription } from "rxjs/Subscription";
// if you want your code to work everytime even though you leave the page
Observable.interval(1000).subscribe(()=>{
this.functionYouWantToCall();
});
Method 2:
// if you want your code to work only for this page
//define this before constructor
observableVar: Subscription;
this.observableVar = Observable.interval(1000).subscribe(()=>{
this.functionYouWantToCall();
});
ionViewDidLeave(){
this.observableVar.unsubscribe();
}
For anyone struggling with this, you can use interval from rxjs like the following :
import { interval } from 'rxjs';
interval(1000).subscribe(x => {
this.myfuntion();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With