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

In JavaScript how to fix the initial difference between display of elements and creation of variables

我正在尝试测量一个盒子出现的时间和用户点击盒子的时间之间的时间,所以我做了这个:

<!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 的警报并且控制台日志显示:

此时通过简单观察,createdTime变量中没有任何内容,即使在调用函数appear()时将框设置为可见,并且该函数也为变量createdTime赋值。还有一点,即使我设置了超时,框显示也非常快,框应该在随机延迟后出现。

我的代码连续第二次运行良好。 我的问题是关于如何avoid/fix这种现象?我做错了什么?

感谢您的关注

在您的 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>