Pausing JavaScript Timers

All over the Web, you’ll find tutorials explaining how to use the setTimeout() method in JavaScript to set up a timer and using clearTimeout() to cancel that timer. Unfortunately, it’s a little more difficult to find information about pausing and resuming those timers.

You could, of course, cancel the timer and start it all over again; which is probably fine if you’re using timers of short durations. However, if you’ve got a 30 second timer or something, you probably don’t want it to start all over again if someone pauses it at the 29-second mark.

There is a way to pause and resume those timers, though. In order to do so, you need to set a variable to capture the timestamp when the timer begins. Then, when you pause the timer, you need to figure out how much time has passed between the start of the timer and now. Once you resume the timer, you’ll simply pass the amount of time that was left to the new timer.