I am working on a simple game: A button starts at the left of the page, and moves to the right each time it is clicked. After 20 clicks, it reaches the end of the page and the "game" is complete. I have gotten this part to work great. To do this, the button actives the moveRight() function on click, which creates a "buffer" (just a div element with some area) that floats to the left of the button.
Now I would like to add a timer. I want to display the time elapsed since the first click, in seconds, on the button as the "game" is being played. I think it would be simple to just update the time each time whenever the button is clicked - I would just add some code to the moveRight() function, which is activated when the button is clicked. HOWEVER, I would like the time to update whenever a new second passes, not when a button is pressed. I don't know how to accomplish this.
I assumed a while-loop would be involved, which would continuously track the time as the game is being played and update it when 1000 milliseconds have passed. But I run into trouble doing this, as the loop doesn't terminate, and besides, I don't know how my script could simultaneously be updating the time and executing the moveRight() function when called for.
Here's most of the document:
JavaScript:
var clickCount = 0;
var startTime;
var gameTime;
var gameStart = false;
var gameOver = false;
function startTimer() {
startTime = new Date();
}
function moveRight() {
if (clickCount == 0) {
startTimer();
}
clickCount++;
var buffer = document.createElement("div");
buffer.style.backgroundColor = "navy";
buffer.style.width = "5%";
buffer.style.height = "50px";
buffer.className = "buffer";
var game = document.getElementById("div2");
var button = document.getElementById("hitThis");
if (clickCount < 20){
game.insertBefore(buffer, button);
}
else if (clickCount == 20) {
gameOver = true;
game.replaceChild(buffer, button);
var congrats = document.createElement("p");
var textNode = document.createTextNode("Congrats! You completed the game.")
congrats.appendChild(textNode);
congrats.style.color = "gold";
game.appendChild(congrats);
}
}
/*
while (!gameOver) {
if (gameStart) {
gameTime = new Date();
timePassed = gameTime.getTime() - startTime.getTime();
document.getElementById("hitThis").innerHTML = (timePassed / 1000);
}
}
*/
HTML:
<body>
<div id="div2">
<p>Goal: Make this go across the screen by clicking it.</p>
<button id="hitThis" onclick="moveRight()">0</button>
</div>
</body>