body { font-family:Helvetica,Tahoma,Arial,sans-serif; color:#333}
JavaScript
/**
* для вопроса https://toster.ru/q/463357
* Как сделать отсчёт времени до определённой даты?
*/
/**
* Из строки времени в формате HH:MM:SS
* делает объект Date
* с ближайшим, после текущего момента, таким временем.
* @param String строка времени
* @return Date Object
*/
function parseTime(s) {
var now = new Date(), D = new Date(now.getTime()), HMS = s.split(':');
if( HMS.length !== 3) throw({message:"неверный формат времени"});
HMS = HMS.map(function(t){return parseInt(t)}); // перевести строки в целые
D.setHours(HMS[0]);
D.setMinutes(HMS[1]);
D.setSeconds(HMS[2]);
if( D < now) D.setDate( D.getDate() + 1);
return D;
}
/**
* добивает число нулями до двух позиций.
* 3 -> 03
* 13 -> 13
*/
function pad(n, len, char) {
var s = n.toString(10);
char = char || '0';
len = len || 2;
if( s.length >= len) return s;
return (Array(1+len).join(char) + n).slice(-len);
}
/**
* Выводит в заданный DOM-элемент время,
* оставшееся до даты-времени в объекте toDate
*/
function countdown( toDate, el) {
var diff = toDate.getTime() - new Date().getTime()
, H
, M
, S = Math.floor(diff/1000)
;
if( S <= 0) { // время прошло
el.innerText = "--:--:-- Ой, всё!";
return;
}
H = Math.floor(S/3600);
S = S % 3600;
M = Math.floor(S/60);
S = S % 60;
el.innerText = '' +pad(H) +':' +pad(M) +':' +pad(S);
setTimeout( countdown.bind(this, toDate, el), 111);
}
countdown(
parseTime('14:00:00'),
document.querySelector('h3#out')
);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Fiddle Pages
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Get Fiddle Pages with PRO
Your fiddles accessible under a custom domain and a vanity path - the simplest hosting for your personal project.