测试计时器应该在页面完全加载到JavaScript后启动


Timer for quiz should start once the page is completley loaded in JavaScript

我正在用PHP开发一个在线问答应用程序,我能够很好地执行它,但问题是,计时器应该只有在加载完整页面时才开始工作。我使用了onload="starttimer()"函数,然后在starttimer()中实现了运行计时器所需的所有代码。当我使用window.stop();停止页面加载时,页面停止加载,但计时器仍在运行。我该怎么做才能避免这种情况?请帮帮我!!

我认为您希望使用setinterval();来控制需要异步运行的计时器,因为javascript中没有任何线程。因此,当你调用window.stop();时,你也可以调用clearInterval();。然后,当你想重新启动计时器时,你可以从头开始,也可以使用html来包含你的值。

在该示例中,计时器最初将以40秒开始

var quiz_interval = setInterval(updateTimer, 1000);
function updateTimer(){
  var time_remaining = parseInt($('#timer').html());
  if(time_remaining  == 0){//dosomething}
  else{ $("#timer").html(time_remaining--);}
  //logic to check if timer has gone down to zero if not write the new number 
  //to the div
}

<html><body>
    <div id="timer">40</div>
</body></html>