为什么setInterval()在angular6中不起作用?

时间:2019-01-19 05:38:07

标签: angular6

当我调用setInterval()函数时,它不起作用。但是,如果我删除clearInterval()函数,它将执行。但是我想清除setInterval以停止无限执行。

    this.interval = setInterval( () => {
          console.log('stoptyping');
          if (msg_area.onfocus) {
              console.log('stoptyping');
              const stdata = {
                  chatId: this.chatId,
                  userId: this.common.getUserId()
              };
              this.chatService.iamStopTyping(stdata);
          } else {
              console.log('interval test1');
              clearInterval(this.interval);
              const stdata = {
                  chatId: this.chatId,
                  userId: this.common.getUserId()
              };
              this.chatService.iamStopTyping(stdata);
          }
      }, 2000);
      console.log('interval test2');
      if (this.interval) {
        clearInterval(this.interval);
      }

1 个答案:

答案 0 :(得分:0)

console.log('interval test2');
if (this.interval) {
  clearInterval(this.interval);
}

这段代码的目的是什么?它会在发生任何有用的事情之前终止您的setInterval(),只需将其删除就可以了。

所以您的解决方案是:

this.interval = setInterval( () => {
      console.log('stoptyping');
      if (msg_area.onfocus) {
          console.log('stoptyping');
          const stdata = {
              chatId: this.chatId,
              userId: this.common.getUserId()
          };
          this.chatService.iamStopTyping(stdata);
          return;
      } 
      console.log('interval test1');
      clearInterval(this.interval);
      const stdata = {
          chatId: this.chatId,
          userId: this.common.getUserId()
      };
      this.chatService.iamStopTyping(stdata);
  }, 2000);