Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 651
Peter Boomsma Avatar asked Sep 29 '17 09:09

Peter Boomsma


People also ask

How do you pause the setInterval?

To pause setInterval() functions with JavaScript, we call the clearInterval function. let doThis = null; const y = () => { //... }; doThis = setInterval(y, 1000); const yStart = () => { doThis = setInterval(y, 1000); }; const yStop = () => { clearInterval(doThis); };

How do you stop setInterval after a condition?

To stop it after running a set number of times, just add a counter to the interval, then when it reached that number clear it.

Can we pause setInterval JavaScript?

You cannot PAUSE the setInterval function, you can either STOP it (clearInterval), or let it run.


2 Answers

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.

like image 188
Robert Broersma Avatar answered Sep 30 '22 01:09

Robert Broersma


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.

like image 39
Aakash Jain Avatar answered Sep 30 '22 00:09

Aakash Jain