typescript IONIC 3 中的 setInterval

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46743354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:58:17  来源:igfitidea点击:

setInterval in IONIC 3

javascriptangulartypescriptionic2ionic3

提问by user3181303

I would like to run a function in every 1 second. After searching, I found setIntervalbut it doesn't work for me.

我想每 1 秒运行一次函数。搜索后,我找到了,setInterval但它对我不起作用。

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

}, 1000);

I also tried this.myfuntionbut it doesn't work too.

我也尝试过,this.myfuntion但它也不起作用。

回答by sebaferreras

The solution is to use Arrow functions:

解决方案是使用箭头函数

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

When using arrow functions, the thisproperty is not overwritten and still references the component instance.

使用箭头函数时,该this属性不会被覆盖并且仍会引用组件实例。

回答by ravi

There are Basically two methods to perform that.

基本上有两种方法可以执行该操作。

Try using observable which will suit best your requirement.

尝试使用最适合您要求的 observable。

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

回答by Fan Cheung

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

试试这个。我认为这是一个范围问题。没有绑定 setInterval 中的范围转到 window 对象

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

回答by Ouamefi

For anyone struggling with this, you can use intervalfrom rxjslike the following :

对于任何为此苦苦挣扎的人,您可以使用rxjs 中的间隔,如下所示:

import { interval } from 'rxjs';

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

回答by Hammad Ahmad

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.

您可以在构造函数或函数内部使用它,然后从外部调用它。