在JavaScript中,如何修复元素显示和变量创建之间的初始差异



我试图测量一个框的点击和用户点击框的时间之间的时间,所以我做了这个:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>JavaScript</title>
  <style type="text/css">
  body{
    background: gray;
  }
  #box{
    width: 100px;
    height: 100px;
    background: red;
    visibility: "hidden";
  }
  </style>
  <script type="text/javascript">
    window.onload = function(){
      var clickedTime; //to store the time when the box is clicked
      var createdTime; //to store the time when the box is created
      var reactionTime; //secs between the box creation and box click
      function appear(){
      //this function is to make the box appear
        setTimeout(function(){
          document.getElementById("box").style.visibility = "visible";
          createdTime = Date.now();
          console.log("createdTime: "+createdTime);
        }, Math.random()*5000);
      }
      document.getElementById("box").onclick = function(){
        //this is to hide the box, make it appear and calculate the reaction time
        clickedTime = Date.now();
        console.log("clickedTime: "+clickedTime);
        reactionTime = (clickedTime - createdTime)/1000;
        console.log("reactionTime: "+reactionTime);
        alert(reactionTime);
        this.style.visibility = "hidden";
        appear();
      }
      appear();
    }
  </script>
</head>
<body>
<div id="box"></div>
</body>
</html>

当用户一开始快速点击框时,就会出现问题,此时会显示带有NaN的警报,控制台日志显示:

  • 点击时间:1428200428320
  • 反应时间:NaN

在这一点上,通过简单的观察,createdTime变量中没有内容,即使在调用函数appear()时框被设置为可见,并且该函数还为变量createdTime赋值。另一点是,即使我设置了超时,框也会显示得很快,框应该在随机延迟后出现。

我的代码连续第二次运行得很好。我的问题是如何避免/解决这种现象?,我做错了什么?

感谢您的关注

在CSS中,更改以下内容:

visibility: "hidden";

…到此:

visibility: hidden;

否则,元素一开始是可见的,因此createdTime可能在第一次单击时尚未初始化。

代码段:

window.onload = function() {
  var clickedTime; //to store the time when the box is clicked
  var createdTime; //to store the time when the box is created
  var reactionTime; //secs between the box creation and box click
  function appear() {
    //this function is to make the box appear
    setTimeout(function() {
      document.getElementById("box").style.visibility = "visible";
      createdTime = Date.now();
      console.log("createdTime: " + createdTime);
    }, Math.random() * 5000);
  }
  document.getElementById("box").onclick = function() {
    //this is to hide the box, make it appear and calculate the reaction time
    clickedTime = Date.now();
    console.log("clickedTime: " + clickedTime);
    reactionTime = (clickedTime - createdTime) / 1000;
    console.log("reactionTime: " + reactionTime);
    alert(reactionTime);
    this.style.visibility = "hidden";
    appear();
  }
  appear();
}
body {
  background: gray;
}
#box {
  width: 100px;
  height: 100px;
  background: red;
  visibility: hidden;
}
<div id="box"></div>

相关内容

最新更新