user3181303
user3181303

Reputation: 371

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.

Upvotes: 8

Views: 17438

Answers (5)

Hammad Ahmad
Hammad Ahmad

Reputation: 204

I used it like this:

import {interval, Subscription} from 'rxjs';

  const source = interval(30000);
        this.subscription = source.subscribe(val => {
          // TODO
        });

you can use it inside the constructor or inside a function and then call it from outside.

Upvotes: 0

Ouamefi
Ouamefi

Reputation: 31

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

import { interval } from 'rxjs';

interval(1000).subscribe(x => {
  this.myfuntion();
});

Upvotes: 3

ravi
ravi

Reputation: 1220

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();
}

Upvotes: 9

sebaferreras
sebaferreras

Reputation: 44659

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.

Upvotes: 13

Fan Cheung
Fan Cheung

Reputation: 11345

try this. I think it's a scope issue. without binding the scope in setInterval goes to the window object

      setInterval(function(){ this.myfunction();}.bind(this), 1000);

Upvotes: 1

Related Questions