user5155835
user5155835

Reputation: 4742

Angular clearinterval not stopping interval

I have following code where I start an Interval for changing page title when the user is on different tab and I receive an event from a Subject:

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

Even after 'clearing interval' gets printed, i.e. when clearInterval() is invoked, still the interval keeps running

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

How can I stop the interval in else block?

Upvotes: 2

Views: 953

Answers (1)

Abhinav Kumar
Abhinav Kumar

Reputation: 3036

ClearInterval clearing the interval but not clearing the subscription, that you have subscribed to. It still there and executing the same line.

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

Upvotes: 2

Related Questions