JSFiddle - React, Tailwind, and code Playground
HTML
<input type="button" id="button" value="reset count">
JavaScript
/*
* @theTimer: we'll assign the setTimeOut function to this
* @total: counter number that's easily editable
* @btn: our button element
*/
var theTimer,
total = 5,
btn = document.getElementById("button");
/* Set the button's click event here to keep
* unneeded markup out of the HTML */
btn.addEventListener("click", function(){ countdown(total) }, false);
/* Dynamically change button text based on @total */
btn.value = "Reset count to " + total;
function countdown(counter) {
/* Exit if nothing to do */
if(counter === 0){
return;
}
/* Clear @theTimer */
clearTimeout(theTimer);
var x = counter;
if (x > 0) {
alert(x + "/" + total);
theTimer = setTimeout(function () {
countdown(x);
}, 2000);
x--;
}
}