關(guān)于setTimeout()多次點(diǎn)擊速度飆升問題!
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>計(jì)時(shí)器</title>
<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>
為什么多次點(diǎn)擊Start速度就會(huì)加快?哪位大神能給個(gè)終極解釋?跪求!
2017-08-01
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>計(jì)時(shí)器</title>
<script type="text/javascript">
? var num=0;
? var i;
? var flag=false;
??
//增加一個(gè)布爾變量用于存儲(chǔ)值代表start是否開始
//這個(gè)方法要置于循環(huán)體外
? function flag1(){
? ? if(flag==false){
? ? ? ?startCount();
? ? ? ?flag=true;
? ? }else{
? ? ? ?return 0;
? ? }
? }
? function startCount(){
? ? document.getElementById('count').value=num;
? ? num=num+1;
? ? i=setTimeout("startCount()",1000);
? }
? function stopCount(){
? ? clearTimeout(i);
? ? flag=false;
? }
</script>
</head>
<body>
? <form>
? ? <input type="text" id="count" />
? ? <input type="button" value="Start" onclick="flag1()" />
? ? <input type="button" value="Stop" onclick="stopCount()" ?/>
? </form>
</body>
</html>
增加一個(gè)開關(guān)裝置即可解決點(diǎn)一次start鍵就多一個(gè)計(jì)數(shù)器增加num值的問題。
2017-05-26
因?yàn)槟阍趕tartCount中又調(diào)用了它本身,所以你多次點(diǎn)擊之后,是多個(gè)計(jì)時(shí)器同時(shí)運(yùn)行的,比如點(diǎn)第一次是一個(gè)計(jì)時(shí)器,再點(diǎn)一下,就是兩個(gè)計(jì)時(shí)器,這時(shí)候每次就是+2,所以速度會(huì)不斷提升