2016-07-15 108 views
0

我的查询非常简单。我能够制作一个倒计时脚本,所以当点击一个按钮时,倒数开始;然而,如果我们继续点击按钮,它只是增加了另一个倒计时,并搅乱了原来的一个。我试图清除间隔,但不知道什么不能让它运行。当我按下开始时倒数开始,但如果你再次点击它,那么你可以自己尝试。我也无法弄清楚如何停止按钮可以结束间隔计时器,我已经尝试cleartInterval();以及。再次按下按钮时开始新的间隔

$("#startClock").click(function(){ 
 
    var counter = document.getElementById('minutes').value; 
 
    setInterval(function() { 
 
    counter--; 
 
     if (counter >= 0) { 
 
     span = document.getElementById("count"); 
 
     span.innerHTML = counter; 
 
     } 
 
     if (counter === 0) { 
 
     span = document.getElementById("count"); 
 
     span.innerHTML = ""; 
 
     } 
 
    }, 1000); 
 

 

 
});
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js?ver=4.1'></script> 
 
Minutes 
 
<select id="minutes"> 
 
    <option value="60">1</option> 
 
    <option value="120">2</option> 
 
    <option value="180">3</option> 
 
    <option value="240">4</option> 
 
    <option value="300">5</option> 
 
    </select> 
 
<button id=startClock >Start</button> 
 
<button id=stopClock >Stop</button> <br/> 
 
<div id="count"></div>

+2

“我曾尝试cleartInterval();” - 这就是你需要做什么,而是你的避风港没有显示你尝试使用它,所以我们不能说出你做错了什么。 – Quentin

回答

1

试试这个:

var clickTimer; 

$("#startClock").click(function(){ 
    if (clickTimer) { 
     clearInterval(clickTimer); 
    } 
    var counter = document.getElementById('minutes').value; 
    clickTimer = setInterval(function() { 
    counter--; 
     if (counter >= 0) { 
     span = document.getElementById("count"); 
     span.innerHTML = counter; 
     } 
     if (counter === 0) { 
     span = document.getElementById("count"); 
     span.innerHTML = ""; 
     } 
    }, 1000); 


}); 

编辑

$("#stopClock").click(function(){ 
if (clickTimer) { 
    clearInterval(clickTimer); 
    clickTimer = undefined; 
} 
}); 
+0

这很快..谢谢! –

+0

另外,是否可以使用“停止”或“暂停”按钮暂停计时器? –

+0

当然,请参阅编辑 –

相关问题