多點(diǎn)一次開始記數(shù)快一次
可以理解成多線程的概念嘛,點(diǎn)一次開始每隔1秒更新一次value,再點(diǎn)一次開始就有兩個(gè)線程同時(shí)每隔1秒更新一次value,也就造成了每0.5秒更新一次
但每點(diǎn)一次停止就慢一次又是怎么回事呢
<!DOCTYPE?HTML> <html> <head> <meta?http-equiv="Content-Type"?content="text/html;?charset=utf-8"> <title>計(jì)時(shí)器</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); ??} </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>
2016-07-16
2016-07-16
全局變量,點(diǎn)擊幾次就會被執(zhí)行幾次,從而造成加速。
在執(zhí)行開始之前先clear掉之前的setTimeout();
你可以在startCount 里的第一句之前先執(zhí)行stopCount()函數(shù)。