js カウントダウンタイマー

var countdown = function(due) {
	var now = new Date();

	var rest = due.getTime() - now.getTime();
		sec = Math.floor(rest / 1000 % 60),
		min = Math.floor(rest / 1000 / 60) % 60,
		hours = Math.floor(rest / 1000 / 60 / 60) % 24,
		days = Math.floor(rest / 1000 / 60 / 60 / 24),
		count = [days, hours, min, sec];

		return count;
}

var goal = new Date(2020, 6, 24);

// console.log(countdown(goal));

var recalc = function() {
	var counter = countdown(goal);
	document.getElementById('day').textContent = addFigure(counter[0]);
	document.getElementById('hour').textContent = ('0' + counter[1]).slice(-2);
	document.getElementById('min').textContent = ('0' + counter[2]).slice(-2);
	document.getElementById('sec').textContent = ('0' + counter[3]).slice(-2);
	refresh();
}

// 更新
var refresh = function() {
	setTimeout(recalc, 1000);
}

// 桁区切り
function addFigure(str) {
    var num = new String(str).replace(/,/g, "");
    while(num != (num = num.replace(/^(-?\d+)(\d{3})/, "$1,$2")));
    return num;
}

recalc();
<div id="timer" class="text-center">あと 
<span id="day"></span> 日
<span id="hour"></span> 時間
<span id="min"></span> 分
<span id="sec"></span> 秒
</div>
あと 1,110 日 22 時間 14 分 18 秒
PAGE TOP