0

Подскажите пожалуста как остановить таймер когда он доходит до 00:00:00, сейчас он идет дальше в минус. Спасибо, в js я новичек

function timer() {
    const newData = new Date('Mar 31 2023 00:00:00');

    const daysVal = document.querySelectorAll('.time-count__days .time-count__val');
    const hoursVal = document.querySelectorAll('.time-count__hours .time-count__val');
    const minutesVal = document.querySelectorAll('.time-count__minutes .time-count__val');
    const secondsVal = document.querySelectorAll('.time-count__seconds .time-count__val');

    const normalize = (n) => n <= 9 ? `0${n}` : n

    const timeCount = () => {
        let now = new Date();
        let leftUntil = newData - now;

        let days = normalize(Math.floor(leftUntil / 1000 / 60 / 60 / 24));
        let hours = normalize(Math.floor(leftUntil / 1000 / 60 / 60) % 24);
        let minutes = normalize(Math.floor(leftUntil / 1000 / 60) % 60);
        let seconds = Math.floor(leftUntil / 1000) % 60;

        daysVal.forEach(dayVal => {
            dayVal.innerHTML = days.toString().replace(/\d/gi, (substring) => `<span>${substring}</span>`);
        });
        hoursVal.forEach(hourVal => {
            hourVal.innerHTML = hours.toString().replace(/\d/gi, (substring) => `<span>${substring}</span>`);
        });
        minutesVal.forEach(minuteVal => {
            minuteVal.innerHTML = minutes.toString().replace(/\d/gi, (substring) => `<span>${substring}</span>`);
        });
        secondsVal.forEach(secondVal => {
            secondVal.innerHTML = seconds.toString().replace(/\d/gi, (substring) => `<span>${substring}</span>`);
        });

    };

    timeCount();
    setInterval(timeCount, 1000);
}
timer()
.time-count__content{
  display: flex;
}

.time-count__item{
  margin: 0px 10px;
}

.time-count__val{
  font-size: 40px;
}

.time-count__text{
  text-align:center;
}
<div class="time-count">
  <div class="time-count__content">
    <div class="time-count__item time-count__days">
      <div class="time-count__val">00</div>
      <div class="time-count__text">д</div>
    </div>
    <div class="time-count__item time-count__hours">
      <div class="time-count__val">00</div>
      <div class="time-count__text">ч</div>
    </div>
    <div class="time-count__item time-count__minutes">
      <div class="time-count__val">00</div>
      <div class="time-count__text">м</div>
    </div>
    <div class="time-count__item time-count__seconds">
      <div class="time-count__val">00</div>
      <div class="time-count__text">с</div>
    </div>
  </div>
</div>

0

1 ответ 1

1

Держи вот такой таймер. t хранит общее время в миллисекундах. Условие проверяет t, когда он ноль или ниже, очищает интервал и функция останавливается.

JS

function timer(id, deadLine) {
  function getTimeRemaining(endTime) {
    let DAYS, HOURS, MINUTES, SECONDS;

    const t = Date.parse(endTime) - Date.parse(new Date());

    if (t <= 0) {
      DAYS = 0;
      HOURS = 0;
      MINUTES = 0;
      SECONDS = 0;
    } else {
      DAYS = Math.floor(t / (1000 * 60 * 60 * 24));
      HOURS = Math.floor((t / (1000 * 60 * 60)) % 24);
      MINUTES = Math.floor((t / 1000 / 60) % 60);
      SECONDS = Math.floor((t / 1000) % 60);
    }

    return {
      t,
      DAYS,
      HOURS,
      MINUTES,
      SECONDS,
    };
  }

  function getZero(num) {
    if (num >= 0 && num < 10) {
      return `0${num}`;
    }

    return num;
  }

  function setClock(selector, endTime) {
    const timer = document.querySelector(selector);
    const days = timer.querySelector('#days');
    const hours = timer.querySelector('#hours');
    const minutes = timer.querySelector('#minutes');
    const seconds = timer.querySelector('#seconds');

    updateClock();
    const timeInterval = setInterval(updateClock, 1000);

    function updateClock() {
      const t = getTimeRemaining(endTime);

      days.innerHTML = getZero(t.DAYS);
      hours.innerHTML = getZero(t.HOURS);
      minutes.innerHTML = getZero(t.MINUTES);
      seconds.innerHTML = getZero(t.SECONDS);

      if (t.t <= 0) {
        clearInterval(timeInterval);
      }
    }
  }

  setClock(id, deadLine);
}

//Вызов функции.

timer('.timer', '2023-04-15');

HTML

<div class="timer">
   <div class="timer__block">
       <span id="days">12</span>
       дней
   </div>
   <div class="timer__block">
       <span id="hours">20</span>
       часов
   </div>
   <div class="timer__block">
       <span id="minutes">56</span>
       минут
   </div>
   <div class="timer__block">
       <span id="seconds">20</span>
       секунд
   </div>
</div>
3
  • не могли бы вы добавить html к коду?не пойму немного как написать html
    – powerg
    25 мар в 17:36
  • @powerg Добавить html.
    – Elmir
    25 мар в 17:43
  • @powerg в deadLine пишите дату в формате "2023-03-25"
    – Elmir
    25 мар в 17:44

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.