【问题标题】:setInterval in IONIC 3IONIC 3 中的 setInterval
【发布时间】:2018-03-26 09:11:53
【问题描述】:

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

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

}, 1000);

我也试过this.myfuntion,但也没用。

【问题讨论】:

    标签: javascript angular typescript ionic2 ionic3


    【解决方案1】:

    我是这样使用的:

    import {interval, Subscription} from 'rxjs';
    
      const source = interval(30000);
            this.subscription = source.subscribe(val => {
              // TODO
            });
    

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

    【讨论】:

      【解决方案2】:

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

      import { interval } from 'rxjs';
      
      interval(1000).subscribe(x => {
        this.myfuntion();
      });
      

      【讨论】:

        【解决方案3】:

        基本上有两种方法可以做到这一点。

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

        方法一:

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

        方法二:

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

        【讨论】:

        • 此功能在应用程序在后台时有效?
        【解决方案4】:

        解决方法是使用Arrow functions

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

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

        【讨论】:

          【解决方案5】:

          试试这个。我认为这是一个范围问题。没有绑定 setInterval 中的作用域就转到窗口对象

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

          【讨论】:

            猜你喜欢
            • 2020-10-22
            • 1970-01-01
            • 2019-08-16
            • 2018-04-04
            • 2018-10-12
            • 1970-01-01
            • 2019-09-25
            • 2018-07-15
            • 1970-01-01
            相关资源
            最近更新 更多