真有意思,谁能告诉我这是为什么?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | <!DOCTYPE HTML> < html > < head > < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" > < title >计时器</ title > </ head > < script type = "text/javascript" > var num=0; var i; function startCount(){ document.getElementById('count').value=num; num=num+1; i=setTimeout("startCount()",1000); } function stopCount(){ clearTimeout(i); i=0;num=0; document.getElementById('count').value=0; } </ script > </ head > < body > < form > < input type = "text" id = "count" /> < input type = "button" value = "Start" onclick = "startCount()" /> < input type = "button" value = "Stop" onclick = "stopCount()" /> </ form > </ body > </ html > |
代码如上,start开始计数,stop停止计数并归零。
点击1次start正常显示,并且stop只需要点击1次就OK。
点击n(n>1)次start时,计数器以n倍速度计数,并且每点击1次stop,计数倍速减一,直至归零。
上一小节就发现了这个问题,请问这是为什么?
我猜一下:是因为每点击一次start就生成了一个计数函数,并且这些计数函数共用同一个全局变量num,然后每点击1次stop就clear一个?是这样吗?~~