JSFiddle - React, Tailwind, and code Playground

by docluv

HTML

<div class="countdown-timer"></div>

CSS

.countdown-timer{
    
    font-size:4em;
    font-weight:800;
}

JavaScript

var cdt = document.querySelector(".countdown-timer"),
    startTime = 180,
    counter = setInterval(function () {

        startTime--;
        if (startTime <= 0) {
            clearInterval(counter);
            //counter ended, do something here
            return;
        }

        cdt.innerHTML = getFormattedTime(startTime);

    }, 1000);


cdt.innerHTML = getFormattedTime(startTime);


function getFormattedTime(currentTime){

    var minutes = 0,
        seconds = 0;
    
    if((currentTime/60) >= 1){

        minutes = Math.floor((currentTime/60));
    
    }
    
    currentTime = currentTime - (minutes * 60);
    
    if(currentTime < 10){
        currentTime = "0" + currentTime;
    }

    return minutes + ":" + currentTime ;

};