我希望我的20秒定时器能够在点击按钮的同时操作20秒警报。我该怎么做呢?
HTML
<aside class="start-box">
<button type="submit" class="btn btn-primary btn-lg" id="toggleBtn" onclick="startClock();"></button>
</aside>
/*Alerts after 20 seconds*/
var alertTimerId = 0;
function startClock () {
setTimeout (gameOver(), 20000);
}
function gameOver ()
{
alert("The time is up!");
}
/*Counts down the timer in the countdown box for 20 seconds*/
var secondsLeft = 20;
var interval =
setInterval(function() {
document.getElementById('countdown').innerHTML = --secondsLeft;
if (secondsLeft <= 0)
{
document.getElementById('countdown').innerHTML = "Gotta catch em' all!";
clearInterval(interval);
}
}, 1000);
答案 0 :(得分:1)
您可以将这两个功能简单地合并到单个setInterval
:
var timer, secondsLeft;
function startClock () {
secondsLeft = 20;
timer = setInterval(function() {
document.getElementById('countdown').innerHTML = --secondsLeft;
if (secondsLeft <= 0)
{
document.getElementById('countdown').innerHTML = "Gotta catch em' all!";
clearInterval(timer);
alert('The time is up'); // alert is now here!
}
}, 1000);
};
&#13;
<aside class="start-box">
<button type="submit" class="btn btn-primary btn-lg" id="toggleBtn" onclick="startClock();">Start</button>
</aside>
<div id='countdown'></div>
&#13;
请注意,它不会发出警报,因为StackOverflow在其代码段中不允许alerts
。
它适用于您的情况或at JSFiddle。