setTimeout() 是属于 window 的方法,该方法用于在指定的毫秒数后调用函数或计算表达式。
语法格式如下:
setTimeout(function[,delay,param1,param2,...]);
setTimeout(function[,delay]);
setTimeout(code[,delay]);
function
在到期时间(delay毫秒)之后执行的函数。
code(可选)
可选语法,可以使用字符串而不是function,在delay毫秒之后编译和执行字符串(但是不推荐,因为有安全风险)。
delay(可选)
延迟的毫秒数 (一秒等于1000毫秒),函数的调用会在该延迟之后发生。如果省略该参数,delay取默认值0,意味着“马上”执行,或者尽快执行。不管是哪种情况,实际的延迟时间可能会比期待的(delay毫秒数) 值长,
param1,...,paramN(可选)
附加参数,一旦定时器到期,它们会作为参数传递给 function 或执行字符串。
- setTimeout 用法一
<!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>
alert("start...");
setTimeout("alert('hello')", 5000);
</script>
</body>
</html>
浏览器打开index.html之后,首先弹出start...,过了5s之后(5000/1000 = 5)弹出“hello”。
注:无需调用,时间一到就会立刻执行setTimeout中的函数。
- setTimeout 用法二
<!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>
alert("start...");
setTimeout(sum, 2000, 1, 2, 1);
function sum(x, y, z) {
alert(x + y + z);
}
</script>
</body>
</html>
运行结果:
setTimeout(sum, 2000, 1, 2);
function sum(x, y, z) {
alert(x + y + z);
}
如果减少一个参数,则运行结果如下:(参数必须保持一致)
- setTimeout 用法三
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=<device-width>, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="jsTest.css">
</head>
<body>
<div class="div" id="divs"></div>
<script>
alert("start...");
var doc=document.getElementById('divs');
setTimeout(function(){
doc.style.backgroundColor="#FFCC80";
},2000, setTimeout(function(){
doc.style.backgroundColor='black';
}, 1000));
</script>
</body>
</html>
.div {
width: 200px;
height: 50px;
background-color: pink;
}
运行结果:
第三个参数也是一个定时器,1s后就会开启。