Cómo crear un temporizador de cuenta regresiva en JavaScript

Este tutorial demostrará cómo crear un temporizador de cuenta regresiva en JavaScript, incluida una función que puede copiar y pegar en su propio código.

El siguiente código se descompondrá creando una función que calcula el tiempo hasta un cierto tiempo futuro y cómo ejecutarlo repetidamente para afectar un temporizador de cuenta regresiva.

Obtener el tiempo restante hasta una determinada fecha/hora

La siguiente función calculará los días, horas, minutos y segundos para una fecha objetivo:

function timeToTarget(countdownString){

    // Convert the string which specifies the target to count down to to a Date object
    let targetDate = new Date(countdownString).getTime();

    // Get the current time
    let now = new Date().getTime();

    //The getTime() method gets a millisecond representation of the time since January 1st, 1970

    //Get the difference between the two
    let difference = targetDate - now;

    // Calculate the days, hours, minutes, seconds difference between the times
    days = Math.floor(difference / (1000 * 60 * 60 * 24));
    hours = Math.floor(difference / (1000 * 60 * 60));
    minutes = Math.floor(difference / (1000 * 60));
    seconds = Math.floor(difference / 1000);

    // Calculate the result
    // As each of the above is the total days, hours, minutes, seconds difference, they need to be subtracted so that they add up to the correct total
    let result =  {
        days: days,
        hours: hours - days * 24,
        minutes: minutes - hours * 60,
        seconds: seconds - minutes * 60,
    };

    // Log the result so we can check that the function is working
    console.log(result);

    // Return the result so that it can be used outside of the function
    return result;
}

Cuenta atrás con setInterval()

El método JavaScript setInterval() llama a una función dada repetidamente, con un retraso de tiempo fijo entre ejecuciones:

setInterval(function(){
    // Code to execute repeatedly here
}, 1000);

Arriba, la función timeToTarget() se llama cada segundo (1000 milisegundos).

Mostrar la cuenta regresiva

Para mostrar los resultados de la cuenta regresiva en una página web, se requiere un elemento HTML:

<div id="countdown-display"></div>

El siguiente JavaScript se puede usar para escribir la información de la cuenta regresiva en el elemento HTML:

document.getElementById("countdown-display").innerHTML =
    '<div>' + result.days + '<span>Days</span></div>' +
    '<div>' + result.hours + '<span>Hours</span></div>' +
    '<div>' + result.result + '<span>Minutes</span></div>' +
    '<div>' + result.seconds + '<span>Seconds</span></div>';

Poniéndolo todo junto

Finalmente, la fecha/hora de la cuenta regresiva debe especificarse como una cadena; estos datos pueden provenir de un selector de fecha u otra entrada del usuario, o de una base de datos:

var countdownString = "Feb 7, 2023 19:30:00";

Poniéndolo todo junto, ¡un temporizador de cuenta regresiva que funciona!

var countdownString = "Feb 7, 2023 19:30:00";

function timeToTarget(countdownString){

    let targetDate = new Date(countdownString).getTime();
    let now = new Date().getTime();
    let difference = targetDate - now;

    days = Math.floor(difference / (1000 * 60 * 60 * 24));
    hours = Math.floor(difference / (1000 * 60 * 60));
    minutes = Math.floor(difference / (1000 * 60));
    seconds = Math.floor(difference / 1000);

    let result =  {
        days: days,
        hours: hours - days * 24,
        minutes: minutes - hours * 60,
        seconds: seconds - minutes * 60,
    };

    console.log(result);

    return result;

}

setInterval(function(){
    let result = timeToTarget(countdownString);
    document.getElementById("countdown-display").innerHTML =
        '<div>' + result.days + '<span> Days</span></div>' +
        '<div>' + result.hours + '<span> Hours</span></div>' +
        '<div>' + result.minutes + '<span> Minutes</span></div>' +
        '<div>' + result.seconds + '<span> Seconds</span></div>' +
        '<div><span>Until </span>' + countdownString + '</div>';

}, 1000);