Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval in IONIC 3

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.

like image 677
user3181303 Avatar asked Oct 14 '17 10:10

user3181303


3 Answers

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.

like image 174
sebaferreras Avatar answered Nov 18 '22 01:11

sebaferreras


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();
}
like image 30
ravi Avatar answered Nov 18 '22 01:11

ravi


For anyone struggling with this, you can use interval from rxjs like the following :

import { interval } from 'rxjs';

interval(1000).subscribe(x => {
  this.myfuntion();
});
like image 2
Ouamefi Avatar answered Nov 18 '22 02:11

Ouamefi