JS之周期函式setInterval
阿新 • • 發佈:2020-09-11
JS內建類:Data,用於獲取時間
原生Data
程式碼示例:
<body>
<script>
var nowTime = new Date();
document.write(nowTime);
</script>
</body>
轉換成本地語言環境
<body> <script> var nowTime = new Date(); /*轉換成本地語言環境的日期格式*/ nowTime = nowTime.toLocaleString(); document.write(nowTime); </script> </body>
自定義日期格式
<body> <script> var nowTime = new Date(); /*自定義日期格式*/ //以全格式返回年資訊 var year = nowTime.getFullYear(); //返回月份(0-11) var month = nowTime.getMonth(); /* 返回的是一週中的第幾天(0-6) var dayOfWeek = nowTime.getDay(); */ //獲取日資訊 var day = nowTime.getDate(); document.write(year + "年" + (month+1) + "月" + day); document.write("<br />"); //獲取毫秒數(從1970年1月1日00:00:00 000到當前系統時間的總毫秒數) document.write(new Date().getTime()); </script> </body>
點選按鈕顯示網頁時鐘
<body> <script> function displayTime(){ var time = new Date(); var strTime = time.toLocaleString(); document.getElementById("timeDiv").innerHTML = strTime; } </script> <input type="button" value="顯示系統時間" onclick="displayTime()" /> <div id="timeDiv"></div> </body>
點選按鈕:
但是時間不會一直重新整理,只能手動點選按鈕,時間才會重新整理。
所以要使用到周期函式setInterval。
HTML DOM setInterval() 方法
概述
1、setInterval()
方法可按照指定的週期(以毫秒計)來呼叫函式或計算表示式。
2、setInterval()
方法會不停地呼叫函式,直到clearInterval()
被呼叫或視窗被關閉。由setInterval()
返回的 ID 值可用作clearInterval()
方法的引數。
clearInterval()
方法
1、可取消由 setInterval() 設定的 timeout。
2、引數必須是由 setInterval() 返回的 ID 值。
3、語法:
clearInterval(id_of_setinterval)
id_of_setinterval 由 setInterval() 返回的 ID 值。
語法
setInterval(code,millisec[,"lang"])
code:必需。要呼叫的函式或要執行的程式碼串。
millisec:必須。週期性執行或呼叫 code 之間的時間間隔,以毫秒計。
程式碼示例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>顯示網頁時鐘</title>
</head>
<body>
<script>
var flag = true;
function displayTime(){
var time = new Date();
var strTime = time.toLocaleString();
document.getElementById("timeDiv").innerHTML = strTime;
}
function start(){
/*
s作為ID值,使用全域性變數
但是多次點選顯示系統時間按鈕的話,
會導致ID值不斷變化,每點一次ID值加1。
這樣clearInterval獲取到的ID值就只是當前的ID值。
之前的對應ID值發生的事件就無法停止。
多次點選沒有把之前的任務覆蓋,而是增加了。
*/
//設定許可權flag,使start、stop都只能執行一次
if(flag){
s = window.setInterval("displayTime()",1000);
flag = false;
}
}
function stop(){
if(!flag){
window.clearInterval(s);
flag = true;
}
}
</script>
<input type="button" value="顯示系統時間" onclick="start()" />
<input type="button" value="停止顯示系統時間" onclick="stop()" />
<div id="timeDiv"></div>
</body>
</html>
點選顯示系統時間(時間會一直變化):
點選停止顯示系統時間,時間會停止變化。