定時器清除不掉
<!doctype html>
<html>
<head>
? ? <meta charset="UTF-8">
? ? <title>Document</title>
? ? <style>
? ? ? ? *{
? ? ? ? ? ? margin:0;
? ? ? ? ? ? padding:0;
? ? ? ? }
? ? ? ? #div1 span{
? ? ? ? ? ? width:20px;
? ? ? ? ? ? height:50px;
? ? ? ? ? ? background-color:blue;
? ? ? ? ? ? position: absolute;
? ? ? ? ? ? top:75px;
? ? ? ? ? ? left:200px;
? ? ? ? }
? ? ? ? #div1{
? ? ? ? ? ? width:200px;
? ? ? ? ? ? height:200px;
? ? ? ? ? ? background-color:red;
? ? ? ? ? ? position: relative;
? ? ? ? ? ? top:0;
? ? ? ? ? ? left:-200px;
? ? ? ? }
? ? </style>
</head>
<body>
<div id="div1"><span id="share">分享</span></div>
</body>
<script>
? ? var oDiv = document.getElementById('div1');
? ? oDiv.onmouseover = function(){
? ? ? ? startMove(10,0);
? ? }
? ? oDiv.onmouseout = function(){
? ? ? ? startMove(-10,-200);
? ? }
? ? var timer = null;
? ? function startMove(speed,value){
? ? ? ? clearInterval(timer);
? ? ? ? var oDiv = document.getElementById('div1');
? ? ? ? timer = setInterval(function(){
? ? ? ? ? ? if(oDiv.offsetLeft == 0){
? ? ? ? ? ? ? ? clearInterval(timer);
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? oDiv.style.left = oDiv.offsetLeft+speed+'px';
? ? ? ? ? ? }
? ? ? ? },30)
? ? }
</script>
</html>
2017-03-16
執(zhí)行函數(shù)時先清除定時器在執(zhí)行定時器 ?避免函數(shù)重復(fù)執(zhí)行
2017-03-16
函數(shù)剛開始執(zhí)行時為什么要清除定時器,指的是第一個
? function startMove(speed,value){
? ? ? ? clearInterval(timer);//這個