typescript - 在 Angular 6 中使用 clearInterval() 停止刷新功能不起作用?
问题描述
我在用户有两个选项的页面上实现刷新功能。 刷新按钮
单击刷新按钮时刷新页面(直接向前)
为用户提供设置刷新频率的选项(在特定间隔后刷新页面的选项) 设置间隔刷新
正如您在图像中看到的那样,我存储在像这样的以下对象中的每个间隔都有不同的值。
timer: RefreshTimer[] = [
{value: 15000, time: '15 Sec'},
{value: 30000, time: '30 Sec'},
{value: 45000, time: '45 Sec'},
{value: 100000, time: '1 min'},
{value: null, time: 'Cancel'}];
我正在使用setInterval()
to calrefresh()
方法,如下所示:
refresh() {
this.router.navigateByUrl('./views/refresh/', { skipLocationChange: true }).then(() => {
console.log(decodeURI(this.location.path()));
this.router.navigate([decodeURI(this.location.path())]);
});}
refreshFrequency(time) {
if(time === null){
this.counter = 110;
}
this.progressInterval = setInterval(() => {
this.counter += 10;
this.refresh();
console.log('this.counter', this.counter);
if(this.counter >= 100){
clearInterval(this.progressInterval);
console.log('cleaned and finished');
}
},time);
}
setInterval()
像这样调用:
<mat-form-field class="timer" style="width: 10px;">
<i class="far fa-clock"></i>
<mat-select class="alarm-dropdown" trigger="alarmTrigger" #alarmSelect>
<mat-option *ngFor="let time of timer"
(click)="refreshFrequency(time.value)"
[value]="time.value">
{{time.time}}
</mat-option>
</mat-select>
</mat-form-field>
这是现在的行为,在我从 DDL 中clearInterval()
选择后不起作用。
1.步骤 1
2.步骤 2
3.步骤 3Cancel
感谢您的帮助。
编辑:这是它的SlackBitz。
解决方案
计时器可能会有所帮助,但因狂奔而臭名昭著,因此请谨慎使用。只要您确保创建的计时器不会超出您的需要,并且您不会忘记现有的计时器,就可以了。像这样的东西:
保存对计时器的引用
this.intervalReference = null;
隔离启动和清理计时器的逻辑。确保它只做一个计时器,否则您的参考将被覆盖。
refreshFrequency(time) {
if (!this.intervalReference && time !== null) {
console.log('Creating a timer. It will run every ' + (time / 1000) + ' seconds');
this.intervalReference = setInterval(() => {
this.counter += 10;
this.refresh();
console.log('this.counter', this.counter);
if (this.counter >= 100) {
clearInterval(this.intervalReference);
console.log('Timer stopped as expected');
this.intervalReference = null;
}
}, time);
} else if (time === null && this.intervalReference) {
console.log('Stopping timer early.');
clearInterval(this.intervalReference);
}
}
推荐阅读
- unity3d - Unity 纹理在垂直表面上显示为线条
- php - Slim 的问题——HttpNotFoundException
- python - 如何使用 Candlestick 从 plotly (Python) 制作动画
- javascript - 如何从浏览器启动批处理文件?
- google-chrome - chrome中页面源和框架源的区别
- python - 如何使用 Python 小写 json dict 中的所有键
- python-3.x - 我不知道为什么这两个代码在 python 中有不同的输出
- python-3.x - 无法使用 Python 登录加密的银行网站
- amazon-web-services - 由于 100% cpu 利用率导致 AWS Aurora 超时
- codeigniter - Codeigniter 用 ID 中的 OR 条件更新数据