JS定时器
js中的定时器有两种:Interval、Timeout
1.Tnterval定时器的开启和关闭
创建定时器:setInterval(函数,时间) — 每隔指定时间就调用指定的函数(时间单位是毫秒),返回一个定时器对象
关闭定时器:clearInterval(定时器对象)
例:
<div id="box" style="background-color: aqua;width: 100px; height: 100px; position: absolute;" top="10px"></div>
<button type="button" onclick="clearInterval(t1)">关闭定时器</button>
1.每过1秒打印
num = 1
t1 = setInterval(function(){
console.log('hello world' + num)
num += 1
},1000)
2.让方块上下移动
top1 = 10
setInterval(function(){
top1 += 10
document.getElementById('box').style.top = top1 + 'px'
},500)
3.让方块变大
width1 = 100
height1 = 100
setInterval(function(){
width1 += 10
document.getElementById('box').style.width = width1 + 'px'
height1 += 10
document.getElementById('box').style.height = height1 + 'px'
},500)
2.Timeout定时器
t2 = setTimeout(function(){
console.log('hello world')
},5000)
定时跳转练习
<body>
<p id="p1">5秒后自动跳转到百度...</p>
</body>
<script type="text/javascript">
time1 = 5
t1 = setInterval(function(){
time1 -= 1
if (time1 == 0){
clearInterval(t1)
// 打开百度
window.location = 'https://www.baidu.com'