So I'm making this reaction game where the player has to click a box as fast as possible. I've displayed the time taken to click the box but I'm trying to displayed the fastest time the player has clicked a box. I would really appreciate your help.
Here's my code:
<body>
<div>
<p>Your time: <span id="time"></span></p>
<p>Highscore: <span id="highscore"></span></p>
<div id="shape"></div>
</div>
<script>
var start = new Date().getTime();
function makeShapeAppear() {
document.getElementById("shape").style.display = "block"
start = new Date().getTime();
}
function appearAfterDelay() {
setTimeout(makeShapeAppear, 1000);
}
appearAfterDelay();
document.getElementById("shape").onclick = function() {
var end = new Date().getTime();
var timeTaken = (end - start)/1000;
document.getElementById("shape").style.display = "none";
document.getElementById("time").innerHTML = timeTaken + "s";
appearAfterDelay();
}
</script>
</body>
To summarize, I want to display the shortest "timeTaken" variable in the highscore id. Thank you in advance.
Store your last time taken if no highscore, if the new time taken is less than your highscore then set the highscore to be the timetaken. Like this.
#shape{
width: 200px;
height: 200px;
background-color:red;
}
<body>
<div>
<p>Your time:
<span id="time"></span>
</p>
<p>Highscore:
<span id="highscore"></span>
</p>
<div id="shape"></div>
</div>
<script>
var highscore;
var start = new Date().getTime();
function makeShapeAppear() {
document.getElementById("shape").style.display = "block"
start = new Date().getTime();
}
function appearAfterDelay() {
setTimeout(makeShapeAppear, 1000);
}
appearAfterDelay();
document.getElementById("shape").onclick = function () {
var end = new Date().getTime();
var timeTaken = (end - start) / 1000;
highscore = (timeTaken < highscore || !highscore ? timeTaken : highscore);
document.getElementById("shape").style.display = "none";
document.getElementById("time").innerHTML = timeTaken + "s";
document.getElementById("highscore").innerHTML = highscore + "s";
appearAfterDelay();
}
</script>
</body>