JSFiddle - React, Tailwind, and code Playground
HTML
<div id="out1"></div>
JavaScript
/*
@name timer
@param number startFrom Starts counting down from this number
@param number delay Seconds to wait before starting a new counter
@param number intervalDelay Milliseconds to wait between countdown
@param number runTimes Optional; Limit of counting. The function stops when it has run <runTimes> times. Default 1 (=one countdown)
@param Boolean noFirstRun Optional; If false, the counter starts off immediately. Default false
*/
function timer(startFrom, delay, intervalDelay, runTimes, notFirstRun){
if(typeof runTimes == "undefined") runTimes = 1;
if(runTimes-- < 0) return;
setTimeout(function(){
var ctn = startFrom;
var timer1 = window.setInterval(function(){
document.getElementById('out1').innerHTML = ctn--;
if(ctn <= 0){
clearInterval(timer1);
timer(startFrom, delay, intervalDelay, runTimes, true);
}
}, intervalDelay);
}, notFirstRun?delay*1000:0);
}
window.onload=function() {
timer(10, 5, 1000, 2);
}