Jony Talassazan Jony Talassazan - 6 months ago 8
Javascript Question

Adding with a button

I currently have a Javascript game where every hour in the game something else happens.

The game is set to start at 12am and I want to make it so that with the click of a button it adds an hour to the time.

My current is as follows

// time-related info
var gameTime = 0; // begin logging time, 12 a.m.
document.getElementById("clock").innerHTML = "Time: " + "12 a.m."; // start the clock at midnight
function updateTime() {
var clock = document.getElementById("clock");
gameTime++;
if (gameTime >= 24) {
gameTime = 0;
clock.innerHTML = "Time: 12 a.m."
} else if (gameTime === 12) {
clock.innerHTML = "Time: " + gameTime + " p.m.";
} else if (gameTime > 12) {
clock.innerHTML = "Time: " + (gameTime - 12) + " p.m.";
} else {
clock.innerHTML = "Time: " + gameTime + " a.m.";
}
}

Answer

// time-related info 
var gameTime = 0;  // begin logging time, 12 a.m.
document.getElementById("clock").innerHTML = "Time: " + "12 a.m."; // start the clock at midnight 
function updateTime() {
var clock = document.getElementById("clock");
gameTime++;
if (gameTime >= 24) {
    gameTime = 0;
    clock.innerHTML = "Time: 12 a.m."
} else if (gameTime === 12) {
    clock.innerHTML = "Time: " + gameTime + " p.m.";
} else if (gameTime > 12) {
    clock.innerHTML = "Time: " + (gameTime - 12) + " p.m.";
} else {
    clock.innerHTML = "Time: " + gameTime + " a.m.";
}
}
<button onclick="updateTime()" >click here</button>
<span Id="clock"/>