Created
May 14, 2021 08:31
-
-
Save b-aleksei/ddb376f98da69bc61662c3876d851eba to your computer and use it in GitHub Desktop.
timer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// const targetDate = new Date(Date.parse('2021-05-17T00:00:00')); // установить дату обратного отсчета | |
const targetDate = new Date(2021, 4, 16); // установить дату обратного отсчета | |
let days; let hours; let minutes; let seconds; // переменные для единиц времени | |
let interval = null; | |
const countdown = document.querySelector('.stock-timer-js'); // получить элемент тега | |
const addZero = (n) => { | |
return (n < 10 ? '0' : '') + n; | |
}; | |
const declineDays = ['день', 'дня', 'дней']; | |
const decline = (number, titles) => { | |
const cases = [2, 0, 1, 1, 1, 2]; | |
return titles[(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]]; | |
} | |
const getCountdown = () => { | |
const currentDate = Date.now(); | |
if (targetDate > currentDate) { | |
let secondsLeft = (targetDate - currentDate) / 1000; // разница в секундах | |
days = Math.round(secondsLeft / 86400) - 1; | |
secondsLeft = secondsLeft % 86400; | |
hours = addZero(Math.round(secondsLeft / 3600)); | |
secondsLeft = secondsLeft % 3600; | |
minutes = addZero(Math.round(secondsLeft / 60)); | |
seconds = addZero(Math.round(secondsLeft % 60)); | |
} else { | |
days = '0'; | |
hours = '00'; | |
minutes = '00'; | |
seconds = '00'; | |
clearInterval(interval); | |
} | |
countdown.innerHTML = `<span>${days} ${decline(days, declineDays)}</span>, <span>${hours}:</span><span>${minutes}:</span><span>${seconds}</span>`; | |
}; | |
getCountdown(); | |
interval = setInterval(function() { | |
getCountdown(); | |
}, 1000); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment