1. 程式人生 > 實用技巧 >JavaScript 29 計時器

JavaScript 29 計時器

示例1:

只執行一次

函式setTimeout(functionname, 距離開始時間毫秒數 );
通過setTimeout在制定的毫秒數時間後,執行一次函式functionname
本例在3秒鐘後,列印當前時間。
解釋:
document.getElementById 獲取id=time的div元素
.innerHTML 修改該元素的內容

<script>
  
function printTime(){
  var d = new Date();
  var h= d.getHours();
  var m= d.getMinutes();
  var s= d.getSeconds();
  document.getElementById(
"time").innerHTML= h+":"+m+":"+s; } function showTimeIn3Seconds(){ setTimeout(printTime,3000); } </script> <div id="time"></div> <button onclick="showTimeIn3Seconds()">點選後3秒鐘後顯示當前時間,並且只顯示一次</button>

示例2:

不停地重複執行函式setInterval(函式名, 重複執行的時間間隔毫秒數 );
通過setInterval重複執行同一個函式,重複的時間間隔由第二個引數指定

<p>每隔1秒鐘,列印當前時間</p>
   
<div id="time"></div>
   
<script>
   
function printTime(){
  var d = new Date();
  var h= d.getHours();
  var m= d.getMinutes();
  var s= d.getSeconds();
  document.getElementById("time").innerHTML= h+":"+m+":"+s;
   
}
   
var t = setInterval(printTime,
1000); </script> <br><br>

示例3:

終止重複執行

通過clearInterval終止一個不斷重複的任務

本例,當秒是5的倍數的時候,就停止執行

<p>每隔1秒鐘,列印當前時間</p>
   
<div id="time"></div>
   
<script>
   
var t = setInterval(printTime,1000);
 
function printTime(){
  var d = new Date();
  var h= d.getHours();
  var m= d.getMinutes();
  var s= d.getSeconds();
  document.getElementById("time").innerHTML= h+":"+m+":"+s;
  if(s%5==0)
     clearInterval(t);
}
   
</script>
<br>

示例4:

不要在setInterval呼叫的函式中使用document.write();

注:部分瀏覽器,比如firefox有這個問題,其他瀏覽器沒這個問題。

假設setInterval呼叫的函式是printTime, 在printTime中呼叫document.write();
只能看到一次列印時間的效果。
這是因為document.write,會建立一個新的文件,而新的文件裡,只有打印出來的時間字串,並沒有setInterval這些javascript呼叫,所以只會看到執行一次的效果。

<p>每隔1秒鐘,通過document.write列印當前時間</p>
 
<script>
 
function printTime(){
  var d = new Date();
  document.write(d.getHours());
  document.write(":");
  document.write(d.getMinutes());
  document.write(":");
  document.write(d.getSeconds());
  document.close();
}
 
var t = setInterval(printTime,1000);
 
</script>