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接口以在组件销毁时停止计时器并清零计数器。

相关内容

热门资讯

透视透视!aapoker怎么开... 透视透视!aapoker怎么开辅助器(透视)免费透视脚本(果然真的有挂);1、任何aapoker怎么...
透视肯定!aapoker破解侠... 透视肯定!aapoker破解侠是真的吗(透视)透视软件(总是真的有挂);1、上手简单,内置详细流程视...
透视插件!aapoker透视方... 透视插件!aapoker透视方法(透视)透视脚本下载(原来真的有挂)1)aapoker透视方法辅助挂...
透视代打!aapoker万能辅... 透视代打!aapoker万能辅助器(透视)万能辅助器(切实存在有挂)1、玩家可以在aapoker万能...
透视挂透视!aapoker脚本... 透视挂透视!aapoker脚本怎么用(透视)辅助(原来真的是有挂);1、下载好aapoker脚本怎么...
透视辅助!aapoker怎么设... 透视辅助!aapoker怎么设置抽水(透视)透视方法(真是真的有挂)1、进入游戏-大厅左侧-新手福利...
透视实锤!aapoker辅助器... 透视实锤!aapoker辅助器怎么用(透视)插件下载(总是真的有挂)1、完成aapoker辅助器怎么...
透视规律!aa poker透视... 透视规律!aa poker透视软件(透视)透视脚本下载(本来是真的有挂)运aa poker透视软件辅...
透视透视!aapoker辅助插... 透视透视!aapoker辅助插件工具(透视)透视方法(原来真的有挂)1、aapoker辅助插件工具a...
透视能赢!aapoker脚本怎... 透视能赢!aapoker脚本怎么用(透视)透视方法(真是真的是有挂)1、下载好aapoker脚本怎么...