How do I pause and resume the setInterval() function using Javascript?
For example, maybe I have a stopwatch to tell you the number of seconds that you have been looking at the webpage. There is a 'Pause' and 'Resume' button. The reason why clearInterval() would not work here is because if the user clicks on the 'Pause' button at the 40th second and 800th millisecond, when he clicks on the 'Resume' button, the number of seconds elapsed must increase by 1 after 200 milliseconds. If I use the clearInterval() function on the timer variable (when the pause button is clicked) and then using the setInterval() function on the timer variable again (when the resume button is clicked), the number of seconds elapsed will increase by 1 only after 1000 milliseconds, which destroys the accuracy of the stopwatch.
So how do I do that?
The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed.
To reset the setInterval timer with JavaScript, we can use the clearInterval function. const myFn = () => { console. log("idle"); }; let myTimer = setInterval(myFn, 4000); //... clearInterval(myTimer); myTimer = setInterval(myFn, 4000);
You could use a flag to keep track of the status:
var output = $('h1'); var isPaused = false; var time = 0; var t = window.setInterval(function() { if(!isPaused) { time++; output.text("Seconds: " + time); } }, 1000); //with jquery $('.pause').on('click', function(e) { e.preventDefault(); isPaused = true; }); $('.play').on('click', function(e) { e.preventDefault(); isPaused = false; });
h1 { font-family: Helvetica, Verdana, sans-serif; font-size: 12px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>Seconds: 0</h1> <button class="play">Play</button> <button class="pause">Pause</button>
This is just what I would do, I'm not sure if you can actually pause the setInterval.
Note: This system is easy and works pretty well for applications that don't require a high level of precision, but it won't consider the time elapsed in between ticks: if you click pause after half a second and later click play your time will be off by half a second.
You shouldn't measure time in interval function. Instead just save time when timer was started and measure difference when timer was stopped/paused. Use setInterval only to update displayed value. So there is no need to pause timer and you will get best possible accuracy in this way.
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