netdjw
netdjw

Reputation: 5997

How to prevent event bubbling in Angular 9 with setInterval?

I have a navbar component in my Angular 9 code, where the user see a countdown timer with their session time. It's count down in every seconds.

My component looks like this:

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.scss']
})
export class NavComponent implements OnInit, OnDestroy {
  timer: any;
  countdownTimer = '';

  constructor() { }

  ngOnInit() {
    this.startTimer();
  }

  ngOnDestroy() {
    this.stopTimer();
  }

  startTimer() {
    this.timer = setInterval(() => {
      this.countdownTimer = this.milisecondsToTime(3600000);
    }, 1000);
  }

  milisecondsToTime(duration: number): string {
    const seconds = Math.floor((duration / 1000) % 60);
    const minutes = Math.floor((duration / (1000 * 60)) % 60);
    const hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

    const hoursString = (hours < 10) ? '0' + hours : hours;
    const minutesString = (minutes < 10) ? '0' + minutes : minutes;
    const secondsString = (seconds < 10) ? '0' + seconds : seconds;

    return hoursString + ':' + minutesString + ':' + secondsString;
  }

  stopTimer() {
    clearTimeout(this.timer);
  }

In the nav.component.html:

      <div>
        Session: {{ countdownTimer }}
      </div>

With this code in every second happening an event bubbling and in the all of my code run functions over and over again. The codebase is getting big enough and this event bubbling slowing down all of the software.

Is there a better way or a best practice to show a countdown timer and don't flood the Angular with event in every seconds?

Upvotes: 0

Views: 451

Answers (2)

Stefan
Stefan

Reputation: 1511

With Angular 9 you can set a new propertyngZoneEventCoalescing to prevent event bubbling. You need to add it within bootstrapModule method.

Example

  platformBrowserDynamic()
  .bootstrapModule(AppModule, { ngZoneEventCoalescing: true })
  .catch(err => console.error(err));

You can read more about this here

Upvotes: 1

HanJeaHwan
HanJeaHwan

Reputation: 1026

I use your code above it does not start a countdown, i not sure what is the 3600000 value stand for, i assume is a duration of countdown, maybe? i created a example not sure it is the solution that you looking for.

https://stackblitz.com/edit/angular-zb7l6w

Upvotes: 0

Related Questions