Angular clearinterval 不停止间隔

Angular clearinterval not stopping interval

我有以下代码,当用户在不同的选项卡上并且我收到来自主题的事件时,我开始更改页面标题的时间间隔:

let that = this;
document.addEventListener('visibilitychange', function(e) {
  if (document.hidden) {
    that.desktopNotificationService.desktopNotifSubject.pipe(take(1)).subscribe((event) => {

      that.blinkInterval = setInterval(() => {
        if (that.titleService.getTitle() === that.origTitle) {
          console.log('setting title notif');
          that.titleService.setTitle(that.appTitleNotif);
        } else {
          console.log('setting title orig');
          that.titleService.setTitle(that.origTitle);
        }
      }, 1000);
    });
  } else {
    console.log('clearing interval');
    clearInterval(that.blinkInterval);
    that.titleService.setTitle(that.origTitle);
  }
}, false);

即使在打印 'clearing interval' 之后,即调用 clearInterval() 时,间隔仍然保持 运行

setting title orig 
setting title notif
setting title orig 
setting title notif
clearing interval
setting title orig 
setting title notif 

如何停止 else 块中的间隔?

ClearInterval 清除间隔但不清除您已订阅的订阅。它仍然在那里并执行同一行。

let that = this;
document.addEventListener('visibilitychange', function(e) {
  let sub ;
  if (document.hidden) {

sub=that.desktopNotificationService.desktopNotifSubject.pipe(take(1)).subscribe((event) => {

      that.blinkInterval = setInterval(() => {
        if (that.titleService.getTitle() === that.origTitle) {
          console.log('setting title notif');
          that.titleService.setTitle(that.appTitleNotif);
        } else {
          console.log('setting title orig');
          that.titleService.setTitle(that.origTitle);
        }
      }, 1000);
    });
  } else {
    console.log('clearing interval');
    clearInterval(that.blinkInterval);
    that.titleService.setTitle(that.origTitle);
    if(sub){
      sub.unsubscribe();// this will do the trick
    }
  }
}, false);