我想要实现的是当您单击此 href <a href="javascript:void(0)" class="pauser">pause/continue</a>
时计时器暂停并在再次按下时继续。
<script>
$(document).ready(function () {
var counter = 10;
var id = setInterval(function() {
counter--;
if(counter > 0) {
var msg = 'You can continue ' + counter + ' seconds';
$('#notice').text(msg);
} else {
$('#notice').hide();
$('#download').show();
clearInterval(id);
}
}, 1000);
});
</script>
如果您需要,我的与 jQuery 相关的 HTML 在这里。
<a href="http://myurl.com" id="download" class="button" style="display: none;font-size:30px;">Continue !!</a><p id="notice">
You can continue in 10 seconds</p>
最佳答案
好吧,我会让你的暂停事件设置一个 bool 值,然后在你递减计数器之前检查这个 bool 值:
<a href="javascript:setPause();" class="pauser">pause/continue</a>
和
var ispaused=false;
function setPause(){
ispaused=!ispaused;
}
和
$(document).ready(function () {
var counter = 10;
var id = setInterval(function() {
if(!ispaused){ ////the only new line I added from your example above
counter--;
if(counter > 0) {
var msg = 'You can continue ' + counter + ' seconds';
$('#notice').text(msg);
} else {
$('#notice').hide();
$('#download').show();
clearInterval(id);
}
}
}, 1000);
});
应该可以吧?
关于javascript - 暂停并继续使用 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8159191/