Javascript 笔记与总结(2-13)定时器 setTimeout 和 setInterval

时间:2023-03-09 16:38:55
Javascript 笔记与总结(2-13)定时器 setTimeout 和 setInterval

定时器可以让 js 效果每隔几秒钟执行一次或者 n 秒之后执行某一个效果。定时器不属于 javascript,是 window 对象提供的功能。

setTimeout 用法:

window.setTimeout('语句',毫秒);   //指定毫秒后执行一次语句

【例】

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#div1{
width: 300px;
height: 300px;
background: blue;
border-bottom: 1px solid black;
}
</style>
</head>
<body>
<p id="p">定时改变文字</p>
<script>
function change(){
document.getElementById("p").innerHTML = "已更换";
}
window.setTimeout("change()", 3000); //3秒之后执行change方法
</script>
</body>
</html>

优化:定时器的效果之上加上倒计时效果

setInterval('语句',毫秒);  //每隔指定毫秒执行一次

清除定时器:

clearInterval();

clearTimeout();

【代码】

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#div1{
width: 300px;
height: 300px;
background: blue;
border-bottom: 1px solid black;
}
</style>
</head>
<body>
<input type="button" name="time" value="5">
<p id="p">定时改变文字</p>
<script>
function change(){
var inp = document.getElementsByName("time")[0];
var time = parseInt(inp.value)-1;
inp.value = time;
if(time == 0){
document.getElementById("p").innerHTML = "已更换";
clearInterval(clock); //清除定时器
}
}
var clock = setInterval("change()", 1000); //每秒钟执行一次
</script>
</body>
</html>

【例】如果不适用 setInterval,只使用 setTimeout,达到每过一段时间执行一次的效果

使用 setTimeout 实现 setInterval 的效果

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#div1{
width: 300px;
height: 300px;
background: blue;
border-bottom: 1px solid black;
}
</style>
</head>
<body>
<input type="button" name="time" value="5">
<p id="p">定时改变文字</p>
<script>
var clock = null;
function change(){
var inp = document.getElementsByName("time")[0];
var time = parseInt(inp.value)-1;
inp.value = time;
if(time == 0){
document.getElementById("p").innerHTML = "已更换";
clearTimeout(clock);
return;
}
setTimeout("change()", 1000);
}
var clock = setTimeout("change()", 1000); //每秒钟执行一次
</script>
</body>
</html>