繁体   English   中英

如何使用 setInterval 防止 Angular 9 中的事件冒泡?

[英]How to prevent event bubbling in Angular 9 with setInterval?

我的 Angular 9 代码中有一个导航栏组件,用户可以在其中看到一个带有会话时间的倒数计时器。 每一秒都在倒计时。

我的组件如下所示:

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

在 nav.component.html 中:

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

这段代码每秒都会发生一个事件冒泡,并且在我所有的代码中一遍又一遍地运行函数。 代码库变得足够大,这个事件冒泡会减慢所有软件的速度。

有没有更好的方法或最佳实践来显示倒数计时器并且不要在每一秒内用事件淹没 Angular?

使用 Angular 9,您可以设置一个新属性ngZoneEventCoalescing以防止事件冒泡。 您需要在bootstrapModule方法中添加它。

例子

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

您可以在此处阅读有关此内容的更多信息

我使用你上面的代码它没有开始倒计时,我不确定 3600000 值代表什么,我认为是倒计时的持续时间,也许? 我创建了一个示例,不确定它是您正在寻找的解决方案。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM