2017-10-14 6 views
1

私は1秒ごとに機能を実行したいと思います。検索後、私はsetIntervalを見つけましたが、それは私のためには機能しません。ION 3のsetInterval

setInterval(function(){ 
    this.myfuntion(); 

}, 1000); 

私もthis.myfuntionを試してみましたが、それはあまりにも動作しません。

答えて

0

これを試してください。スコープの問題だと思う。 setIntervalでスコープを結合するウィンドウオブジェクト

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

に行くことなく、解決策は、Arrow functionsを使用することです:

setInterval(() => { 
    this.myfuntion(); // Now the "this" still references the component 
}, 1000); 

矢印機能を使用する場合は、thisプロパティが上書きされず、まだ言及コンポーネントインスタンス

1

基本的に2つの方法があります。

あなたの要件に最も適した観察可能なものをお試しください。

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

方法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(); 
} 
関連する問題