Angular可以启动计时器但无法停止它
创始人
2024-10-27 20:01:32
0

可以使用RxJS中的Interval Observable来代替原生的setInterval函数,并使用takeUntil操作符来停止计时器。 示例代码如下:

import { Component, OnDestroy } from '@angular/core'; import { interval, Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators';

@Component({ selector: 'app-counter', template: {{ counter }} }) export class CounterComponent implements OnDestroy { counter = 0; private interval$ = interval(1000); private stop$ = new Subject();

start() { this.interval$ .pipe(takeUntil(this.stop$)) .subscribe(() => { this.counter++; }); }

stop() { this.stop$.next(); this.stop$.complete(); this.counter = 0; }

ngOnDestroy() { this.stop$.next(); this.stop$.complete(); } }

在上面的代码中,我们定义了一个Interval Observable来代替setInterval函数,并在start函数中使用takeUntil操作符来停止计时器。我们还定义了一个stop$Subject来控制计时器应停止,并在stop函数中调用了next和complete方法以确保计时器被完全停止。我们也实现了ngOnDestroy接口以在组件销毁时停止计时器并清零计数器。

相关内容

热门资讯

透视解谜!wepoker免费脚... 透视解谜!wepoker免费脚本咨询(透视)wpk免费辅助,教程窍要(有挂详细)-哔哩哔哩1、打开软...
透视开挂!hhpoker到底可... 透视开挂!hhpoker到底可以透视吗(透视)智星菠萝透视,教程项目(揭秘有挂)-哔哩哔哩1、完成h...
透视解密!wejoker辅助软... 透视解密!wejoker辅助软件视频(透视)pokernow辅助控制,教程诀窍(有挂讲解)-哔哩哔哩...
透视辅助!wepoker有没有... 透视辅助!wepoker有没有透视方法(透视)拱趴大菠萝万能挂,教程要领(有挂秘诀)-哔哩哔哩1、让...
透视分享!wepoker透视脚... 透视分享!wepoker透视脚本免费使用视频(透视)智星德州插件,教程妙计(有挂讲解)-哔哩哔哩在进...
透视普及!wepoker有辅助... 透视普及!wepoker有辅助功能吗(透视)wpk德州局透视,教程窍要(有挂助手)-哔哩哔哩1、we...
透视推荐!云扑克有透视吗(透视... 透视推荐!云扑克有透视吗(透视)wepokerplus万能挂,教程诀窍(有挂规律)-哔哩哔哩1、该软...
透视解谜!拱趴大菠萝机器人(透... 透视解谜!拱趴大菠萝机器人(透视)wpk辅助是什么,教程法门(有挂秘诀)-哔哩哔哩1、游戏颠覆性的策...
透视详细!aa poker透视... 透视详细!aa poker透视软件(透视)红龙poker辅助,教程大纲(有挂存在)-哔哩哔哩1、aa...
透视科普!wepoker透视视... 透视科普!wepoker透视视频(透视)wepoker透视脚本免费下载,教程机巧(有挂方略)-哔哩哔...