// ==========================================================
// 計時器功能
// ==========================================================
;(function($) {
list_Obj.happenAfterSearch = function(){
$('.countdown-timer').each(function(i, ele) {
const startTime = new Date($(ele).data('start'));
const endTime = new Date($(ele).data('end'));
// setInterval(countDown, 1000, ele, endTime, startTime)
setTimeout(countDown, 1000, ele, endTime, startTime)
countDown(ele, endTime, startTime);
});
}
$('.countdown-timer').each(function(i, ele) {
const startTime = new Date($(ele).data('start'));
const endTime = new Date($(ele).data('end'));
// setInterval(countDown, 1000, ele, endTime, startTime)
setTimeout(countDown, 1000, ele, endTime, startTime)
countDown(ele, endTime, startTime)
});
function countDown(target, endTime, startTime) {
const nowTime = Date.now()
if($(target).children('.timer-string').length) {
$(target).children('.timer-string').remove()
}
if(startTime > nowTime) {
$(target).prepend('尚未開始')
return setTimeout(countDown, 1000, target, endTime, startTime)
} else if(nowTime > endTime) {
$(target).prepend('優惠結束')
return false
} else {
const leftTime = endTime - nowTime;
const leftSec = Math.floor(leftTime / 1000) % 60;
const leftMin = Math.floor(leftTime / 1000 / 60) % 60;
const leftHour = Math.floor(leftTime / 1000 / 60 / 60) % 24;
const leftDay = Math.floor(leftTime / 1000 / 60 / 60 / 24);
$(target).children('.second-box').text(padLeft(leftSec, 2));
$(target).children('.minute-box').text(padLeft(leftMin, 2));
$(target).children('.hour-box').text(padLeft(leftHour, 2));
$(target).children('.date-box').text(padLeft(leftDay, 2));
return setTimeout(countDown, 1000, target, endTime, startTime)
}
}
function padLeft(content, length, symbol) {
let targetStr = content.toString()
let letter = symbol || 0
if(targetStr.length < length) {
targetStr = letter + targetStr
return padLeft(targetStr, length, letter)
} else {
return targetStr
}
}
})($)