gpt4 book ai didi

javascript - 我如何调用第二个函数来进行点击操作?

转载 作者:行者123 更新时间:2023-12-03 08:21:35 25 4
gpt4 key购买 nike

我希望我的 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);

最佳答案

您可以简单地将这两个函数组合到单个 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);
};
<aside class="start-box">
<button type="submit" class="btn btn-primary btn-lg" id="toggleBtn" onclick="startClock();">Start</button>
</aside>

<div id='countdown'></div>

请注意,它不会发出警报,因为 StackOverflow 不允许在其代码片段中出现警报。

它适用于您的情况或此处,at JSFiddle .

关于javascript - 我如何调用第二个函数来进行点击操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33729043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com