Не могу сделать отсчет времени от конкретной даты

116
17 января 2021, 15:00

/* 
 function repit(timeRace) { 
 setInterval(timeLeft(),500); 
} 
предполагаемая функция обновления счётчика 
*/

День добрый. Пытаюсь реализовать функцию, которая отсчитывает время до предстоящего события. Саму функцию реализовал, но при этом хочу, чтобы счётчик шёл постоянно,а не при каждом обновлении страницы. Знаю, что это можно сделать как-то через setInterval(), но не получается. Функция timeLeft(timeRace), где timeRace-время события, до которого идёт отсчет, вычитается, соответственно,настоящее время.

function timeLeft(timeRace) { 
  let dateToday = new Date(); 
  if (dateToday > timeRace) { 
    return "Гонка уже прошла" 
  } else { 
    let daysLag = Math.floor((timeRace.getTime() - dateToday.getTime()) / (1000 * 3600 * 24)); 
    let hoursLag = Math.floor((timeRace.getTime() - dateToday.getTime()) / (1000 * 3600) - daysLag * 24); 
    let minitesLag = Math.floor((timeRace.getTime() - dateToday.getTime()) / (1000 * 60) - daysLag * 24 * 60 - hoursLag * 60); 
    let secondsLag = Math.floor((timeRace.getTime() - dateToday.getTime()) / (1000) - daysLag * 24 * 60 * 60 - hoursLag * 60 * 60 - minitesLag * 60); 
    hoursLag = checkTime(hoursLag); 
    minitesLag = checkTime(minitesLag); 
    secondsLag = checkTime(secondsLag); 
    return daysLag + ":" + hoursLag + ":" + minitesLag + ":" + secondsLag; 
  } 
} 
 
function checkTime(i) { 
  if (i < 10) { 
    i = "0" + i 
  } 
  return i; 
}

Answer 1

function timeLeft(timeRace) { 
  let dateToday = new Date(); 
  if (dateToday > timeRace) { 
    return "Гонка уже прошла" 
  } else { 
    let daysLag = Math.floor((timeRace.getTime() - dateToday.getTime()) / (1000 * 3600 * 24)); 
    let hoursLag = Math.floor((timeRace.getTime() - dateToday.getTime()) / (1000 * 3600) - daysLag * 24); 
    let minitesLag = Math.floor((timeRace.getTime() - dateToday.getTime()) / (1000 * 60) - daysLag * 24 * 60 - hoursLag * 60); 
    let secondsLag = Math.floor((timeRace.getTime() - dateToday.getTime()) / (1000) - daysLag * 24 * 60 * 60 - hoursLag * 60 * 60 - minitesLag * 60); 
    hoursLag = checkTime(hoursLag); 
    minitesLag = checkTime(minitesLag); 
    secondsLag = checkTime(secondsLag); 
    return daysLag + ":" + hoursLag + ":" + minitesLag + ":" + secondsLag; 
  } 
} 
 
function checkTime(i) { 
  if (i < 10) { 
    i = "0" + i 
  } 
  return i; 
} 
 
var timeRace = new Date(2019, 5, 1); 
setInterval(function(){ 
  document.getElementById("message").textContent = timeLeft(timeRace); 
}, 1000);
<span id="message"></span>

READ ALSO
Отскакивающий от дива мячик

Отскакивающий от дива мячик

Нужно, чтобы мячик отскакивал от синего дива, а не проходил сквозь него

87
Зачем в данном случае удалять класс?

Зачем в данном случае удалять класс?

Непонятен фрагмент кода в строке 1Надо реализовать подсветку ячейки при клике

131