Peter Boomsma
Peter Boomsma

Reputation: 9846

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:

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.

Upvotes: 11

Views: 22696

Answers (3)

Aakash Jain
Aakash Jain

Reputation: 1973

This is not possible since setInterval neither allows you to pause, nor even allows you to fetch the time elapsed/remaining in the interval. 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.

Upvotes: 7

krozero
krozero

Reputation: 6453

here's example in plunker [https://plnkr.co/edit/SEh8lBCfl8L9rwHqyWJb?p=preview][1]

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

you can set variable for interval.

Upvotes: 0

Robert Broersma
Robert Broersma

Reputation: 860

Assuming you want to pause adding time to your currentTime, and not actually pause the interval:

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.

Upvotes: 19

Related Questions