Call a function every 10 seconds Angular2

后端 未结 5 2094
臣服心动
臣服心动 2020-12-05 07:18

I\'m trying to create a Timer that calls an API call every 10 seconds, I\'m using setTimeOut but the thing is that it becomes an infin

5条回答
  •  情话喂你
    2020-12-05 07:40

    There is nothing wrong with setTiimeout, It’s just a bug in your codes. This is indeed an infinite loop(recursive function without a base condition) as you don't have any base condition there.

    So, setTimeout will keep on calling onTimeOut() after every 1 second as it does not know where to stop. Just use a base condition to finish the recursion when you switch to other pages.

     private flag: boolean;
    
     ngOnInit() {
            this.flag = true;
     }
    
     ngOnDestroy() {
            this.flag = false;
     }
     onTimeOut() {
            this.ApiCall().then(
            success => {
            if(success ['ok'] == 0){
                this.navCtrl.push(myPage);
            }
            },
            error => { console.log(error); });
        }
         setTimeout(() => {
         if(this.flag){
            this.onTimeOut();
         }
        }, 1000);
        }
    

    ngOnDestroy method will set the flag as false and the last call of the recursive function won't go inside the if block and as there is nothing to be executed after that, It will return back (previous state of it) and will clear it up from the stack, This process will be repeated till the stack is cleared up(same thing would happen to previous version of it which is now on the top of the stack and thus will clear up the stack one by one recursively).

提交回复
热议问题