在使用定时器的过程中会产生定时器的累加,往往定时器的累加会加快定时器的计算,导致时间不准确
错误案例
在下面的代码中,多次进入box后会加快控制台输出num。
<!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 type="text/css">
.box{
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<script type="text/javascript">
window.onload = function(){
var box = document.getElementsByClassName('box')[0];
var time = 0;
var num = 0;
box .onmouseover = function(){
time = setInterval(function(){
num +=1;
console.log(num);
},1000);
}
}
</script>
</body>
</html>
解决定时器的累加主要思想是:先清除定时器,后设置定时器
例如:当鼠标进入box时,先进行定时器的清除,然后在设置定时器
box .onmouseover = function(){
clearInterval(time);
time = setInterval(function(){
num +=1;
console.log(num);
},1000);
}