要想知道它們是怎麼停止的,首先我們要了解它們的運行機制和原理:
先來了解 setInterval :
--------------------------------------------------------------------------------------------------------
1,HTML DOM setInterval() 方法
參數 | 描述 |
---|---|
code | 必需。要調用的函數或要執行的代碼串。 |
millisec | 必須。週期性執行或調用 code 之間的時間間隔,以毫秒計。 |
參數 | 描述 |
---|---|
id_of_setinterval | 由 setInterval() 返回的 ID 值。 |
參數 | 描述 |
---|---|
code | 必需。要調用的函數後要執行的 JavaScript 代碼串。 |
millisec | 必需。在執行代碼前需等待的毫秒數。 |
參數 | 描述 |
---|---|
id_of_setinterval | 由 setTimeout() 返回的 ID 值。該值標識要取消的延遲執行代碼塊。 |
實例
下面的例子每秒調用一次 timedCount() 函數。您也可以使用一個按鈕來終止這個定時消息:
<html>
<head>
<script type="text/javascript">
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",1000)
}
function stopCount()
{
clearTimeout(t)
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
</body>
</html>
提示和註釋
提示:setTimeout() 只執行 code 一次。如果要多次調用,請使用 setInterval() 或者讓 code 自身再次調用 setTimeout()。
實例,這個例子,在你點擊按鈕 5 秒鐘後會彈出一個提示框:
<html> <head> <script type="text/javascript"> function timedMsg() { var t=setTimeout("alert('5 seconds!')",5000) } </script> </head> <body> <form> <input type="button" value="Display timed alertbox!" onClick="timedMsg()"> </form> <p>Click on the button above. An alert box will be displayed after 5 seconds.</p> </body> </html>
-----------------------------
2,HTML DOM clearTimeout() 方法
定義和用法
clearTimeout() 方法可取消由 setTimeout() 方法設置的 timeout。
語法
clearTimeout(id_of_settimeout)
如何停止:
下面這個例子將每隔 50 毫秒調用 clock() 函數。您也可以使用一個按鈕來停止這個 clock:
<html>
<body>
<input type="text" id="clock" size="35" />
<script language=javascript>
var int=self.setInterval("clock()",50)
function clock()
{
var t=new Date()
document.getElementById("clock").value=t
}
</script>
</form>
<button onclick="int=window.clearInterval(int)">
Stop interval</button>
</body>
</html>
--------------------------------------------------------------------------------------------------------
再來了解 setTimeout :
1,HTML DOM setTimeout() 方法
定義和用法
setTimeout() 方法用於在指定的毫秒數後調用函數或計算表達式。
語法
setTimeout(code,millisec)
返回值
一個可以傳遞給 Window.clearInterval() 從而取消對 code 的週期性執行的值。
---------------------------------------------------
2,HTML DOM clearInterval()方法
定義和用法
clearInterval() 方法可取消由 setInterval() 設置的 timeout。
clearInterval() 方法的參數必須是由 setInterval() 返回的 ID 值。
語法
clearInterval(id_of_setinterval)
定義和用法
setInterval() 方法可按照指定的週期(以毫秒計)來調用函數或計算表達式。
setInterval() 方法會不停地調用函數,直到 clearInterval() 被調用或窗口被關閉。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的參數。
語法
setInterval(code,millisec[,"lang"])