[js] Создание таймера

Подготовка

Добавим в проект новую зависимость:

npm i dayjs

Код

Функция таймера

timer.js
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat";

/*
 * Перевод миллисекунд в объект день, час, минута, секунда
 */
function getObjectTime(ms) {
    const checkNum = (num) => {
        return num < 0 ? 0 : num;
    }

    const daysMs = ms % (24*60*60*1000);
    const hoursMs = ms % (60*60*1000);
    const minutesMs = ms % (60*1000);

    const days = checkNum(Math.floor(ms / (24*60*60*1000)));
    const hours = checkNum(Math.floor(daysMs / (60*60*1000)));
    const minutes = checkNum(Math.floor(hoursMs / (60*1000)));
    const seconds = checkNum(Math.floor(minutesMs / 1000));

    return {
        days,
        hours,
        minutes,
        seconds,
    }
}

export default function timer(selector) {
    dayjs.extend(customParseFormat);

    const dateTimer = selector.dataset.timer;
    const future = dayjs(dateTimer, "DD-MM-YYYY HH:mm Z");
    const now = dayjs(new Date());
    const diff = future.diff(now);
    const diffTime = getObjectTime(diff);

    selector.querySelector("[data-day]").innerHTML = diffTime.days.toString();
    selector.querySelector("[data-hour]").innerHTML = diffTime.hours.toString();
    selector.querySelector("[data-minutes]").innerHTML = diffTime.minutes.toString();
    selector.querySelector("[data-seconds]").innerHTML = diffTime.seconds.toString();
}

Вызов таймера

index.js
import timer from "./timer.js";

const dateTimer = document.querySelector("[data-timer]");

if(dateTimer) {
    setInterval(() => timer(dateTimer), 1000);
}

Шаблон

<div class="timer-wrapper" data-timer="10-02-2077 10:00 +03:00">
    <div class="timer-item" data-day>00</div>
    <div class="timer-item" data-hour>00</div>
    <div class="timer-delimer">:</div>
    <div class="timer-item" data-minutes>00</div>
    <div class="timer-delimer">:</div>
    <div class="timer-item" data-seconds>00</div>
</div>