setTimeout 和 setInterval
-
setTimeout
和setInterval
,也是浏览器中的内置函数,属于JavaScript
代码 -
setTimeout
:表示多久之后执行-
语法
setTimeout(func, time)
, time 是毫秒 -
可以通过
clearTimeout
函数对setTimeout
进行取消
-
-
setInterval
:间隔多长时间循环执行-
语法
setInterval(func, time)
, time 是毫秒 -
可以通过
clearInterval
函数对setInterval
进行取消
-
一、代码实战
代码的详细解读,可以参考视频教程。
新建 html 文件 21-setTimeout.html
,编写下方程序,运行看看效果吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="cancelExe()">取消执行</button>
<script type="text/javascript">
function outFunc(){
alert("setTimeout")
}
let to = setTimeout(outFunc,3000)//3秒
function inFunc(){
alert("setInterval")
}
let ti = setInterval(inFunc,3000)
function cancelExe(){
clearTimeout(to)
clearInterval(ti)
}
</script>
</body>
</html>