clearInterval在我的角度代码中不起作用

时间:2019-06-03 09:04:28

标签: javascript angular typescript

所有文件运行完毕后,数组this.currentlyRunning变空并且其长度为零。

 if(numberOfFiles === 0) {
            clearInterval(this.repeat);
          }

我用console.log测试了if是否执行,如果if条件的评估结果为true,但仍然无法清除间隔。如果我在那里console.log,那么它将继续输出该值。如果我将return语句放在clearInterval下面,则仅以下代码不会执行,但计时器将一直运行直到返回。

仅当提交多个文件以供运行时才会发生,这意味着,如果currentRunning数组具有多个对象。它仅在清空数组的末尾发生

 export class ...... {
     repeat: any;   
     currentlyRunning = [];

OnInit(){......}

      checkFileStatus() {
        let index = 0;
        this.repeat = setInterval(() => {
          let numberOfFiles = this.currentlyRunning.length;
          if(numberOfFiles === 0) {
            clearInterval(this.repeat);
          }
        let file_id = {
          userFileId: this.currentlyRunning[index].id
        }
          this.auth.verifyProgress(file_id).subscribe((res: any)=>{
                if(res.userFileStatus === "Completed") {
                 ..........
                this.currentlyRunning.splice(index, 1);
                  });
                }
                index  = index + 1;
                  if(index >= numberOfFiles) {
                    index = 0;
                  }
                  if(this.currentlyRunning.length === 0) {
                    clearInterval(this.repeat);
                    return;
                }
             },(err)=>{ 
              index  = index + 1;
                if(index >= numberOfFiles) {
                  index = 0;
                }
                if(this.currentlyRunning.length === 0) {
                  clearInterval(this.repeat);
                  return;
               }
            });
        }, 4000);
        }

        }

1 个答案:

答案 0 :(得分:0)

我的猜测是您的auth.verifyProgress具有堆栈执行功能,一旦完成就应该销毁。

尝试一下,添加一个unsubscribe()

const listener = this.auth.verifyProgress(file_id).subscribe((res: any)=>{ if(res.userFileStatus === "Completed") { .......... this.currentlyRunning.splice(index, 1); }); } index = index + 1; if(index >= numberOfFiles) { index = 0; } if(this.currentlyRunning.length === 0) { clearInterval(this.repeat); return; } listener.unsubscribe(); }, (err)=>{ index = index + 1; if(index >= numberOfFiles) { index = 0; } if(this.currentlyRunning.length === 0) { clearInterval(this.repeat); return; } listener.unsubscribe(); });