一.setInterval()與setTimeout()的定義:javascript
二.setInterval()與setTimeout()的使用:java
1.setInterval()與clearInterval()函數
<button id="btn" onclick="stopTime()">按鈕</button> <p id="ptime"></p> <script type="text/javascript"> var mytime = setInterval(function(){ getTime(); //函數調用 },1000); //1000毫秒 function getTime(){ var d = new Date(); var t = d.toLocaleTimeString(); //將日期對象時分秒轉換成字符串 document.getElementById('ptime').innerHTML = t; } function stopTime(){ clearInterval(mytime); }
1.setTimeout()與clearTimeout()spa
<body onload="getHello()"> <button id="btn" onclick="stopHello()">按鈕</button> <p id="ptime"></p> <script type="text/javascript"> var myinfo; function getHello(){ alert("hello"); myinfo = setTimeout(function(){getHello()},3000); } function stopHello(){ clearTimeout(myinfo); }
3.區別對象
setTimeout()是對自身的調用執行,setInterval()是延遲執行blog