setTimeout(code, millisec)——在指定時間後執行一次程式碼;code 與 millisec 皆為必填。
clearTimeout(setTimeoutId)——取消 setTimeout。
setInterval(code, millisec)——每隔指定毫秒循環執行程式碼;code 與 millisec 皆為必填。
clearInterval(intervalId)——取消 setInterval。
其實用 setTimeout 搭配巢狀呼叫,也能實現 setInterval 的效果。以下是一個利用 setTimeout 做倒數計時的範例:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>無標題文檔</title>
<script type="text/javascript">
var c = 6;
var t;
function timedCount() {
var time = document.getElementById('txt').value;
if (time > 0) {
document.getElementById('txt').value = c;
c = c - 1;
t = setTimeout("timedCount()", 1000);
} else {
clearTimeout(t);
}
}
</script>
</head>
<body>
<form>
<input type="button" value="開始計時!" onClick="timedCount()">
<input type="text" id="txt" value="6">
</form>
</body>
</html>