Skip to content

Instantly share code, notes, and snippets.

@amorkovin
Last active April 10, 2020 08:42
Show Gist options
  • Save amorkovin/fbe794bb7dabf275532e081cb420098e to your computer and use it in GitHub Desktop.
Save amorkovin/fbe794bb7dabf275532e081cb420098e to your computer and use it in GitHub Desktop.
Таймер JavaScript
// Таймер будет вставлен в начало node wrapper_timer.
// Через 1 минуту в коносоль выведется test123. Таймер на 1 минуту будет отображен в начале node footer
const footer = document.querySelector('.footer');
man_get_timer('test_timer', footer, 1, function(){
console.log('test123');
});
// Таймер будет вставлен в начало wrapper_timer.
function man_get_timer(timer_id, wrapper_timer, min_timer_pause, after_stop_timer_function) {
let exp_time = new Date();
exp_time.setMinutes(exp_time.getMinutes() + min_timer_pause);
// Опция скрывает счетчик часов из таймера. Обычно достаточно считать минуты.
const not_show_hours = true;
let style_hours = '';
if (not_show_hours) {
style_hours = ' style="display: none;"';
}
//Создаю и вставляю HTML таймера
const timer = document.createElement('div');
timer.setAttribute('id', timer_id);
timer.innerHTML = '<span>Осталось <span class="timer"><span class="days countdown-time" style="display: none;"></span><span' + style_hours + '><span class="hours countdown-time"></span>:</span><span class="minutes countdown-time"></span>:<span class="seconds countdown-time"></span></span></span>';
wrapper_timer.prepend(timer);
initializeClock(timer_id, exp_time, after_stop_timer_function);
}
function initializeClock(id, endtime, after_stop_timer_function) {
const clock = document.getElementById(id);
const daysSpan = clock.querySelector('.days');
const hoursSpan = clock.querySelector('.hours');
const minutesSpan = clock.querySelector('.minutes');
const secondsSpan = clock.querySelector('.seconds');
function updateClock() {
const t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
after_stop_timer_function();
}
}
updateClock();
let timeinterval = setInterval(updateClock, 1000);
}
function getTimeRemaining(endtime) {
const t = Date.parse(endtime) - Date.parse(new Date());
const seconds = Math.floor((t / 1000) % 60);
const minutes = Math.floor((t / 1000 / 60) % 60);
const hours = Math.floor((t / (1000 * 60 * 60)) % 24);
const days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment