做倒計時只需要兩個知識點:
setTimeout:每隔一秒更新一次顯示。Date 物件:計算目標時間與當前時間的差值。以下以「距離元旦還有幾天」為例:
<!DOCTYPE html>
<html>
<head>
<title>example.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script>
// 定義計時器,每隔 1 秒調用 timer 函數
var timerCount = window.setTimeout("timer()",1000);
function timer(){
var date = new Date("2017","1","1","0","0","0");
var deadlineTime = date.getTime();
var nowDate = new Date();
var nowTime = nowDate.getTime();
var distTime = deadlineTime - nowTime;
// 判斷是否到達時間期限
if(distTime > 0){
var d = Math.floor(distTime/1000/3600/24);
var h = Math.floor(distTime/1000/3600%24);
var m = Math.floor(distTime/1000/60%60);
var s = Math.floor(distTime/1000%60);
var str = "距離2017年元旦還有" + d + "天" + h + "時" + m + "分" + s + "秒";
document.getElementById("timeout").innerHTML = str;
timerCount = window.setTimeout("timer()",1000);
} else{
// 到達時間期限時清除計時器
window.clearTimeout(timerCount);
alert("時間已到");
}
}
</script>
</head>
<body>
<p id="timeout"></p>
</body>
</html>
% 24、% 60 取餘,才能正確拆成天時分秒。setTimeout,形成連續更新;時間一到就 clearTimeout 收尾,避免定時器殘留。setInterval 搭配 clearInterval,並注意 Date 的月份參數是從 0 開始,new Date(2017,1,1) 其實是二月一日,這是常見的取捨陷阱。