關于setTimeout()多次點擊速度飆升問題!
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>計時器</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>
為什么多次點擊Start速度就會加快?哪位大神能給個終極解釋?跪求!
2017-08-01
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>計時器</title>
<script type="text/javascript">
? var num=0;
? var i;
? var flag=false;
??
//增加一個布爾變量用于存儲值代表start是否開始
//這個方法要置于循環體外
? 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>
增加一個開關裝置即可解決點一次start鍵就多一個計數器增加num值的問題。
2017-05-26
因為你在startCount中又調用了它本身,所以你多次點擊之后,是多個計時器同時運行的,比如點第一次是一個計時器,再點一下,就是兩個計時器,這時候每次就是+2,所以速度會不斷提升