如何在此反应时间生成器上添加平均时间

时间:2018-07-25 08:59:32

标签: javascript timer average display

下面的代码来自一个简单的反应计时器。当形状随机出现时,用户将尽快单击它。然后显示他们的时间。是否有任何简单的编码(因为这是我目前所学的全部),以使其也显示平均时间甚至最佳时间?

<html>
    <head>  
        <title>Reaction Timer</title>
        <style type="text/css">
            body {
                font-family: sans-serif;
            }

            #shape {            
                width: 200px;
                height: 200px;
                background-color: red;
                cursor: pointer;
                display: none;
                position: relative;
            }

            .bold {
                font-weight: bold;
            }

        </style>
    </head>

    <body>
        <h1> Test Your Reactions!</h1>      
        <p>Click on the shapes as fast as you can! How fast can you do it?</p>
        <p class="bold">Your time: <span id="timeTaken"></span></p>
        <div id="shape"></div>
        <script type="text/javascript">
            var start = new Date().getTime();

            function getRandomColor() {
              var letters = '0123456789ABCDEF';
              var color = '#';
              for (var i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
              }
              return color;
            }

            function makeShapeAppear() {
                var top = Math.random() * 400;
                var left = Math.random() * 400;
                var width = (Math.random() * 200) + 100;

                if (Math.random() > 0.5) {
                    document.getElementById("shape").style.borderRadius = "50%";
                } else {        
                    document.getElementById("shape").style.borderRadius = "0";
                }

                document.getElementById("shape").style.backgroundColor = getRandomColor();
                document.getElementById("shape").style.top = top + "px";
                document.getElementById("shape").style.left = left + "px";
                document.getElementById("shape").style.width = width + "px";
                document.getElementById("shape").style.height = width + "px";
                document.getElementById("shape").style.display = "block";
                start = new Date().getTime();
            }

            function appearAfterDelay() {
                setTimeout(makeShapeAppear, Math.random() * 2000);
            }

            appearAfterDelay();
            document.getElementById("shape").onclick = function() {
                document.getElementById("shape").style.display = "none";
                var end = new Date().getTime();
                var timeTaken = (end - start) / 1000;
                document.getElementById("timeTaken").innerHTML = timeTaken + "s";
                appearAfterDelay();
            }
        </script>
    </body>
</html>

0 个答案:

没有答案