简体   繁体   English

如何使用Angular暂停setInterval?

[英]How to pause setInterval with Angular?

I have a play and a pause button: 我有一个播放和一个暂停按钮:

<div *ngIf="!playToggle">
    <button (click)="playTimeLine(); playToggle = true">
        <i class="fa fa-play" aria-hidden="true"></i>
    </button>
</div>
<div *ngIf="playToggle">
    <button (click)="pauseTimeLine(); playToggle = false">
        <i class="fa fa-pause" aria-hidden="true"></i>
    </button>
</div>

If the play button is clicked it calls the playTimeLine function: 如果单击播放按钮,则调用playTimeLine函数:

currentTime = 0;

playTimeLine(value) {

    setInterval(() => {
        this.currentTime = this.currentTime + 10;
        console.log(this.currentTime);
    }, 1000);
}

I would like to add a pause function that pauses the interval. 我想添加暂停功能,暂停间隔。 But it also makes it possible to resume it from the point it was paused. 但它也可以从暂停时恢复它。

Assuming you want to pause adding time to your currentTime, and not actually pause the interval: 假设您要暂停为currentTime添加时间,而不是实际暂停间隔:

Add an attribute to your class declaring the interval: 在类中添加一个声明间隔的属性:

interval;

Store the interval in the attribute in your play function: 将间隔存储在播放功能的属性中:

this.interval = setInterval(() => {
    this.currentTime = this.currentTime + 10;
    console.log(this.currentTime);
}, 1000);

In a pause function, clear the interval: 在暂停功能中,清除间隔:

pauseTimeLine(value) {
    clearInterval(this.interval);
}

EDIT: Note that this is not very precise timing, but depending on the purpose of your code it could be workable. 编辑:请注意,这不是非常精确的时间,但根据您的代码的目的,它可以是可行的。

This is not possible since setInterval neither allows you to pause, nor even allows you to fetch the time elapsed/remaining in the interval. 这是不可能的,因为setInterval既不允许您暂停,也不允许您获取间隔中经过/剩余的时间。 You can simply create and clear intervals. 您可以简单地创建和清除间隔。

If you wanted to stop the interval, you could do the following: 如果要停止间隔,可以执行以下操作:

timer = null;

startTimer() {
  this.stopTimer();
  this.timer = setInterval(() => { /* do something */ }, 1000);
}

stopTimer() {
  if (this.timer) {
    clearInterval(this.timer);
  }
}

If you wish to implement a pausable timer, you will need to create your own class and use it. 如果您希望实现可暂停的计时器,则需要创建自己的类并使用它。

Also consider using RxJS timers instead of setInterval for the implementation of your timer. 还可以考虑使用RxJS计时器而不是setInterval来实现计时器。

here's example in plunker [ https://plnkr.co/edit/SEh8lBCfl8L9rwHqyWJb?p=preview][1] 这里是plunker的例子[ https://plnkr.co/edit/SEh8lBCfl8L9rwHqyWJb?p=preview][1]

[1]: https://plnkr.co/edit/SEh8lBCfl8L9rwHqyWJb?p=preview

you can set variable for interval. 您可以为间隔设置变量。

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

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