setInterval():定时器
回去重复执行某一功能
参数1:每次执行的具体任务,自定义
参数2:每次执行的间隔时间,单位毫秒
setTimeout():只执行一次的定时器
参数1:执行的具体时间,
参数2:间隔多久(延迟多久)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box{
width: 200px;
height: 200px;
background-color: pink;
line-height: 200px;
text-align: center;
font-size: 30px;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
box=document.getElementsByClassName("box")[0];
box.innerHTML = Math.floor(Math.random()*250);
console.log(box)
var s = 0;
var num = 0;
var time =setInterval(function(){ //参数1:功能自定义
s = Math.floor(Math.random()*250);
box.innerHTML = s;
num++; //变量自增
if(num>6){ //判断是否达到指定条件
clearInterval(time); //清除定时器
time = null //置空
}
//清除定时器:
// 需要有记录器(变量自增),来记录运行次数,到达指定条件时触发
// 定义定时器时,需要定义变量来保存这个定时器(例如: time)
// 然后使用clearInterval()方法。来清除这个变量中的定时器,并将这个变量 置空(time = null)
},1000) //参数2:间隔的时间
var time_two = setTimeout(function(){
box.style.backgroundColor = "red";
},2500)
</script>
</body>
</html>
来源:CSDN
作者:Jason–json
链接:https://blog.csdn.net/weixin_46146313/article/details/104128647