周期性定时器:设置一个时间间隔,时间一到,做指定的事情,然后重新计时
-
设置:
var timer = setInterval(函数, 时间)
-
清除:
clearInterval(timer)
<html>
<head>
<meta charset="utf-8" />
<title>周期性定时器</title>
<style>
div {
margin: 100px auto;
width: 300px;
height: 200px;
background: greenyellow;
color: white;
font-size: 50px;
text-align: center;
line-height: 200px;
}
</style>
</head>
<body>
<div>0</div>
</body>
<script>
var timer = null
var oDiv = document.getElementsByTagName('div')[0]
oDiv.onmouseover = function () {
// 先保存起来,然后再使用
var _this = this
// 创建定时器
timer = setInterval(function(){
// 定时器任务函数中的this没有意义
var num = parseInt(_this.innerText)
num++
_this.innerText = num
}, 1000)
}
oDiv.onmouseout = function () {
// 清除定时器
clearInterval(timer)
}
</script>
</html>
鼠标放上面数字自动增加,鼠标移开停止增加数字。