Инициализация таймера:
timer({
container: '.timer',
date: '09/30/2018',
template: function() {
return `
<div>
<span v-time-days></span>
:
<span v-time-hours></span>
:
<span v-time-minutes></span>
:
<span v-time-seconds></span>
</div>
`;
},
finish: function() {
return '<span>Время вышло</span>';
}
});
Сама плагин-функция таймера:
function timer(options) {
var setting = extend({
container: '.timer',
date: '09/30/2018',
template: function() {},
finish: function() {}
}, options || {});
var general = {
context: document.querySelector(setting.container),
date: new Date(setting.date).getTime(),
time: {},
inverval: 0
};
general.context.innerHTML = setting.template.call(general.context);
initTimer();
general.interval = setInterval(initTimer, 1e3);
function initTimer() {
var remaining = general.date - Date.now();
general.time = getTimeObject(remaining);
if (remaining <= 1e3) {
var html = setting.finish.call(general.context);
if (html) general.context.innerHTML = html;
clearInterval(general.inverval);
} else {
changeTime(general.time);
}
}
function changeTime(time) {
['days', 'hours', 'minutes', 'seconds'].forEach(function(name) {
[].forEach.call(general.context.querySelectorAll('[v-time-' + name + ']'), function(node) {
if (node.innerText !== time[name]) node.innerText = time[name];
});
});
}
function getTimeObject(time) {
return doubleDigits({
seconds: Math.floor((time / 1e3) % 60),
minutes: Math.floor((time / 1e3 / 60) % 60),
hours: Math.floor((time / (1e3 * 60 * 60) % 24)),
days: Math.floor(time / (1e3 * 60 * 60 * 24))
});
}
function doubleDigits(time) {
if (typeof time === 'object') {
for (var item in time) {
time[item] = time[item] < 10 ? '0' + time[item] : String(time[item]);
}
} else {
time = time < 10 ? '0' + time : time;
}
return time;
}
function extend(out) {
out = out || {};
for (var i = 1; i < arguments.length; i++) {
var obj = arguments[i];
if (!obj) continue;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (typeof obj[key] === 'object') {
out[key] = extend(out[key], obj[key]);
}
else {
out[key] = obj[key];
}
}
}
}
return out;
}
}