我该如何调用第二个函数来操作点击

How would I call the second function to operate on click?

本文关键字:函数 第二个 操作 调用 何调用      更新时间:2023-09-26

我希望我的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不允许在其代码段中出现alerts

它将在您的情况下或在JSFiddle工作。