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.
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); };
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.
You cannot PAUSE the setInterval function, you can either STOP it (clearInterval), or let it run.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With