JSFiddle - React, Tailwind, and code Playground
by timdown
HTML
<input type="button" value="pause" onclick="timer.pause()">
<input type="button" value="resume" onclick="timer.resume()">
<div>Count: <b id="counter">0</b></div>
JavaScript
function RecurringTimer(callback, delay) {
var timerId, start, remaining = delay;
this.pause = function() {
window.clearTimeout(timerId);
remaining -= new Date() - start;
};
var resume = function() {
start = new Date();
timerId = window.setTimeout(function() {
remaining = delay;
resume();
callback();
}, remaining);
};
this.resume = resume;
this.resume();
}
var timer = new RecurringTimer(function() {
document.getElementById("counter").innerHTML = ++count;
}, 1000);
var count = 0;