Angular интервал очистки без остановки - PullRequest
1 голос
/ 15 января 2020

У меня есть следующий код, где я начинаю интервал для изменения заголовка страницы, когда пользователь находится на другой вкладке, и я получаю событие от субъекта:

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

Даже после того, как напечатан «интервал очистки», то есть когда вызывается clearInterval (), интервал продолжает работать

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

Как остановить интервал в блоке else?

1 Ответ

2 голосов
/ 15 января 2020

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);
...