1. window对象允许以指定的时间间隔执行代码。这些时间间隔称为定时事件。
2. setTimeout()和clearTimeout()方法
2.1. setTimeout()方法在等待指定的毫秒数后执行函数。
2.2. 语法
setTimeout(function, milliseconds)
第一个参数是要执行的函数。
第二个参数指示执行之前的毫秒数。
2.3. clearTimeout()方法停止执行setTimeout()中规定的函数。
2.4. clearTimeout()使用从setTimeout()返回的变量:
myVar = setTimeout(function, milliseconds);
clearTimeout(myVar);
3. setInterval()和clearInterval()方法
3.1. setInterval()方法在每个给定的时间间隔重复给定的函数。
3.2. 语法
setInterval(function, milliseconds)
第一个参数是要执行的函数。
第二个参数每个执行之间的时间间隔的长度。
3.3. clearInterval()方法停止setInterval()方法中指定的函数的执行。
3.4. clearInterval()方法使用从setInterval()返回的变量:
myVar = setInterval(function, milliseconds);
clearInterval(myVar);
4. 例子
4.1. 代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<title>定时事件</title>
</head>
<body>
<!-- 这里不要加var, 挺奇怪 -->
<button onclick="sayHelloTimeout = setTimeout(sayHello, 3000)">3秒后, 对大家说hello</button>
<button onclick="clearTimeout(sayHelloTimeout)">停止3秒后对大家说hello</button>
<button onclick="sayHelloInterval = setInterval(countTime, 1000)">开始计时</button>
<button onclick="clearInterval(sayHelloInterval)">停止计时</button>
<br /><br /><div id="helloDiv">对大家说:</div>
<div id="myDiv">0</div>
<script type="text/javascript">
var helloDiv = document.getElementById('helloDiv');
var myDiv = document.getElementById('myDiv');
function sayHello() {
helloDiv.innerHTML += 'hello erverybody';
}
function countTime() {
myDiv.innerHTML = ++myDiv.innerHTML;
}
</script>
</body>
</html>
4.2. 效果图