# 定时器和延时器
# 定时器
# 设置定时器
使用 setInterval() 函数设置可以重复执行的函数, 传入参数可以规定调用间的时间间隔
举例:每隔一秒自增变量a并打印
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var a = 0;
setInterval(function() {
console.log(a)
}, 1000);
</script>
</body>
</html>
setInterval 除了以上两个参数外,还可以接收第3、4….N个参数,他们将被顺序传给回调函数内部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
setInterval(function(a, b) {
console.log('a=', a, ";b=", b);
}, 1000, 12, 14);
</script>
</body>
</html>
# 清除定时器
使用clearInterval() 用于清除一个定时器
举例: 编写两个按钮, 点击按钮 开始, 就开始计数, 点击按钮 暂停,结束计数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3 id="incrNum">0</h3>
<button id="start">开始</button>
<button id="pause">暂停</button>
<script>
var incrNum = document.getElementById("incrNum");
var start = document.getElementById("start");
var pause = document.getElementById("pause");
var a = 0;
var timer;
start.onclick = function() {
// 防止重复点击,计数器叠加
clearInterval(timer);
timer = setInterval(function() {
incrNum.innerText = a ++;
}, 1000)
}
pause.onclick = function() {
clearInterval(timer);
}
</script>
</body>
</html>
# 延时器
# 设置延时器
使用 setTimeout() 函数可以设置一个延时器,当指定事件到了之后,会执行一次函数(不会重复执行)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setTimeout</title>
</head>
<body>
<script>
setTimeout(function() {
console.log('hello world');
}, 2000)
</script>
</body>
</html>
setTimeout 函数 和 setInterval() 一样,除了以上两个参数外,还可以接收第3、4….N个参数,他们将被顺序传给回调函数内部
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setTimeout</title>
</head>
<body>
<script>
setTimeout(function(a, b) {
console.log('hello world, a:', a, "b:", b);
}, 2000, 10, 20);
</script>
</body>
</html>
# 清除定时器
clearTimeout() 函数用于清除延时器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setTimeout</title>
</head>
<body>
<script>
var timeout = setTimeout(function() {
console.log('hello world');
}, 2000);
// 清除后, 永远不会打印 hello world
clearTimeout(timeout);
</script>
</body>
</html>
← DOM操作之事件传播 浏览器内置对象 →