javascript - 我的 JavaScript 计时器不起作用

标签 javascript html web timer

我正在尝试创建一个小型 JavaScript 计时器,其中用户回答问题的时间有限,如果用户没有及时回答,他们将被引导回主页。我从代码中得到的关于计时器的信息实际上就是“[]”。

我的代码:

    <DOCTYPE! html>

<html>

<head>

<link rel="stylesheet" type="text/css" href="style_q1.css">

<script type="text/javascript">

var time="60";
var min="0";
var sec="0";

function startTimer() {
      min=parseInt(timer/60);
      sec=parseInt(timer%60);

      if(timer<1){

        window.location="index.html";

      }

      document.getElementById("time").innerHTML = "<b> Time Left: </b>"+min.toString()+":"+sec.toString();
      timer--;
      setTimeout(function(){
      startTimer();
      }, 1000) ;
}

</script>


</head>

<body onload="startTimer();">

  <div id="top">


  </div>


  <div id="logo">

<h1 style="color:white;"> Question 1 -  Geography </h1>

  </div>

  <div id="game_area">

 <center>  <h2> What is the capital of Ireland? </h2> </center>



  </div>


  <div id="time">

      <center> <b>[<span id="time" ></span></b>]</center>

  </div>

  </body>

  </html>

最佳答案

只需使用 setInterval() ,它几乎就是为此而设计的:

更新:请记住在时间到时停止 setinterval 过程。 使用此方法clearInterval()停止该过程。

var secondsLeft = 60;

function startTimer() {
      var min=parseInt(secondsLeft/60);
      var sec=parseInt(secondsLeft%60);

      if(secondsLeft<1){
        alert('timer expired');

        //window.location="index.html";

      }

      document.getElementById("time").innerHTML = "<b> Time Left: </b>"+min.toString()+":"+sec.toString();
      secondsLeft--;
}

setInterval(startTimer, 1000);
<DOCTYPE! html>

<html>

<head>
<link rel="stylesheet" type="text/css" href="style_q1.css">
</head>

<body onload="startTimer();">

  <div id="top">


  </div>


  <div id="logo">

    <h1 style="color:white;"> Question 1 -  Geography </h1>

  </div>

  <div id="game_area">

 <center>  <h2> What is the capital of Ireland? </h2> </center>



  </div>
  <div id="time">

      <center> <b>[<span id="time" ></span></b>]</center>

  </div>

  </body>

  </html>

关于javascript - 我的 JavaScript 计时器不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48308080/

相关文章:

javascript - 如何从 Angular 中的另一个 Controller 内的 Controller 访问对象

javascript - 基于 RIA REST 的应用程序可以选择哪些 JS 库

javascript - 从 Javascript 和 HTML 运行 Unix 命令

php - 如何检查 YouTube channel 名称是否存在?

javascript - 从 HTML/文本中提取 URL,但如果 URL 仅显示部分内容,如 "/secondpage.html"?

javascript - 在 Javascript 中为函数内的 CSS 文本设置样式

javascript - 将 js 代码转换为 jQueryMobile 时出错

html - 需要帮助让列堆叠链接 flex 成一行

html - CSS 格式问题

visual-studio - 在 Azure 中使用 Visual Studio Online 加载测试性能计数器