简体   繁体   English

如何清除Stackblitz(Angular)中的计时器/间隔

[英]How to clear timers/intervals in Stackblitz (Angular)

When developing an app with a timer in Stackblitz, the interval is not cleared between runs. 在Stackblitz中使用计时器开发应用程序时,两次运行之间的间隔不会清除。 As in, in the Stackblitz project settings, I specified to reload on saves. 就像在Stackblitz项目设置中一样,我指定要在保存时重新加载。 But when the app reloads, the old intervals are all still active. 但是,当应用程序重新加载时,旧的间隔仍然处于活动状态。

In the ngOnInit method I set a timer on an interval with the code: window.setInterval(this.tick, 1000); 在ngOnInit方法中,我使用以下代码在一个间隔上设置一个计时器: window.setInterval(this.tick, 1000); And in the function tick() I added logging to see what was going on by adding console.log('log information 1'); 在函数tick()中,我通过添加console.log('log information 1');添加了日志记录以查看发生了什么console.log('log information 1'); statements. 陈述。 Then I change the content of my tick() function to console.log('log information 2'); 然后,将tick()函数的内容更改为console.log('log information 2'); And afterwards I can see both 'Log information 1' and 'Log information 2' messages appear in my console every second. 之后,我每秒都可以看到“日志信息1”和“日志信息2”消息同时出现在控制台中。

I tried keeping track of the intervals by adding a timer variable like: this.appTimer = window.setInterval(this.tick, 1000); 我尝试通过添加计时器变量来跟踪间隔,例如: this.appTimer = window.setInterval(this.tick, 1000); and then clearing the old timer before creating a new one by window.clearInterval(this.appTimer); 然后清除旧计时器,然后再通过window.clearInterval(this.appTimer);创建一个新计时器window.clearInterval(this.appTimer); Before doing anything else on a new run. 在重新运行其他任何操作之前。 But ofcourse because it is a new run, the variable appTimer is still empty. 但是当然,因为它是新运行,所以变量appTimer仍然为空。

Is there a way to just clear all active intervals when reloading Stackblitz? 重新加载Stackblitz时是否有一种方法可以清除所有活动间隔? Refreshing the browser does the trick, but that starts and stops the dev server which seems like overkill. 刷新浏览器可以解决问题,但这会启动和停止开发服务器,这似乎有些过头。

Try using an observable interval instead, and use a destroyable observable with takeUntil() . 尝试改用可观察的间隔,并通过takeUntil()使用可takeUntil()的可观察的间隔。

import {interval} from 'rxjs';

@Component({...})
export class ExampleComponent implements OnInit, OnDestroy {
   private destroyed = new Subject();
   ngOnDestroy() { this.destroyed.next(); }
   ngOnInit() {
      interval(1000).pipe(
         takeUntil(this.destroyed)
      ).subscribe(v => console.log(v));
   }
}

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

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