JSFiddle - React, Tailwind, and code Playground
HTML
<label for="counter">Counter:</label>
<input id="counter" type="text" readonly><br>
<label for="status">Status:</label>
<input id="status" type="text" value="Running" size="40" readonly><br>
<div id="message">Click anywhere in the result box and hit "p" to stop the counter</div>
CSS
label {
display: inline-block;
width: 5em;
}
#message {
padding-top: 5em;
text-align: center;
}
JavaScript
var $counter = $("#counter");
var $status = $("#status");
var counter = 1;
var counterOn = true;
var delay = 3000;
var lastRun;
var tempDelay;
var intervalId;
function incrementCounter() {
$counter.val(counter++);
timeoutId = setTimeout(incrementCounter, delay);
lastRun = new Date();
}
function toggleCounter() {
var curTime = new Date();
counterOn = !counterOn;
if (counterOn) {
$status.val("Running");
lastRun = curTime.valueOf() + tempDelay - delay;
timeoutId = setTimeout(incrementCounter, tempDelay);
} else {
clearTimeout(timeoutId);
tempDelay = delay - (curTime.valueOf() - lastRun);
$status.val("Paused: " + (tempDelay/1000).toFixed(1) + " seconds remain");
}
}
$(document).keydown(function(e) {
if (e.which === 80) {
toggleCounter();
}
});
incrementCounter();