setTimeout 只执行一次的定时器
clearTimeout 关闭只执行一次的定时器
setInterval 反复执行的定时器
clearInterval 关闭反复执行的定时器
定时器的基本用法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定时器的基本用法</title>
<style type="text/css">
</style>
<script type="text/javascript">
//单次定时器
var timer = setTimeout(function(){
alert('hello!');
}, 3000);
//清除单次定时器
clearTimeout(timer);
//反复循环定时器
var timer2 = setInterval(function(){
alert('hi~~~');
}, 2000);
//清除反复循环定时器
clearInterval(timer2);
</script>
</head>
<body>
</body>
</html>
定时器动画
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>定时器动画</title>
<style type="text/css">
.box{
width: 100px;
height: 100px;
background-color: gold;
position: fixed;
left: 20px;
top: 20px;
}
</style>
<script type="text/javascript">
window.onload = function(){
var oBox = document.getElementById('box');
var left = 20;
//反复循环定时器,每30毫秒修改一次盒子的left值
var timer = setInterval(function(){
left += 2;
oBox.style.left = left + 'px';
//当left值大于700时停止动画(清除定时器)
if(left > 700){
clearInterval(timer);
}
},30);
}
</script>
</head>
<body>
<div class="box" id="box"></div>
</body>
</html>
网友评论