時(shí)間停止和繼續(xù)問題,代碼貼在下面,為何先點(diǎn)擊繼續(xù)時(shí)間按鈕就不能停止了,停止按鈕無效了,怎么回事?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>定時(shí)器</title>
<script type="text/javascript">
? var attime,stop;
? function clock(){
??? var time=new Date();?????????
??? attime=time.getHours()+":"
????????? +time.getMinutes()+":"
????????? +time.getSeconds();
??? document.getElementById("clock").value = attime;
? }
? stop=setInterval(clock,100);
? function fun1(){
???? clearInterval(stop);
???? alert("時(shí)間停止!");
? }
?? function fun2(){
???? stop=setInterval(clock,100);
???? alert("時(shí)間繼續(xù)!");
? }
</script>
</head>
<body>
<form>
<input type="text" id="clock" size="50"? />
<input type="button" value="點(diǎn)擊我停止時(shí)間" onclick="fun1()">
<input type="button" value="點(diǎn)擊我繼續(xù)時(shí)間" onclick="fun2()">
</form>
</body>
</html>
2015-12-08
因?yàn)槟阆赛c(diǎn)繼續(xù)就等于增加了一個(gè)setInterval,并將這個(gè)新加的賦值給了stop,那么你每次clearInterval就只能清除掉這個(gè)新加的,而清除不掉原來有的,因?yàn)闆]有變量指向老的setInterval了,所以最好在fun2的一開始把stop清除掉,然后再增加setInterval賦值給stop
2015-12-08
在你的fun2里添加?clearInterval(stop);