Create Countdown timer in javascript

Asked

Viewed 816 times

-1

1 answer

1


Good morning,

You need to set a range of 1 second so that a function is called constantly. To do this, use setInterval;

Try something like that:


var tempoEmMinutos = 15;
var expiracao = new  Date(new Date().getTime() + tempoEmMinutos * 60000);

contador = window.setInterval(function(){
    faltam = expiracao - new Date();
    if (faltam <= 0){
        window.clearInerval(contador);
        console.log("Prazo expirado");
    }
    minutos = Math.floor(faltam / 60000);
    segundos = faltam % 60000;
    tempoRestante = `${minutos}:${segundos.toString().substring(0,2)}`;

    //abaixo, coloque no lugar de 'tempo' o id do elemento do html que contem o timer
    document.getElementById('tempo').innerText = tempoRestante;
    console.log(tempoRestante);
}, 1000);

Example in operation

Browser other questions tagged

You are not signed in. Login or sign up in order to post.