Reputation:
I am trying to make my program to call a gameOver() function if the player does not click the elements within 5 seconds. I have the javascript listening for a click event and pushing the data into another function handleClick() (this function just checks if the sequence is correct). I am unsure as to add a timeOut so that if the user doesnt click within 5 seconds i call another function called gameOver()
tileCon.addEventListener('click', e => {
const { tile } = e.target.dataset;
if (tile) handleClick(tile);
});
tileCon is my container for my clickable elements in my index.html.
Im thinking I would have to create a separate function but i am unsure how to implement it
Upvotes: 0
Views: 645
Reputation: 180
You can try something like
const button = document.querySelector(".clickme")
let timer
function timerStart(){
timer ? clearTimeout(timer) : "";
timer = setTimeout(gameOver,5000)
console.log("clicked")
}
function gameOver(){
console.log("Game Over")
}
button.addEventListener('click',timerStart)
.clickme{
height :2rem;
width:6rem;
background: blue;
}
<button class="clickme">Click me </button>
Upvotes: 2
Reputation: 11486
You can use this piece of code:
let timout;
let isGameStarted = false;
const output = document.getElementById('output');
function startOrContinueGame() {
if (!isGameStarted) {
isGameStarted = true;
timeout = setTimeout(gameOver, 5000);
output.innerHTML = "Game started!";
} else {
clearTimeout(timeout);
timeout = setTimeout(gameOver, 5000);
output.innerHTML = "Game still running.";
}
}
function gameOver() {
if (timeout) {
clearTimeout(timeout);
}
isGameStarted = false;
output.innerHTML = "Game over!";
}
<button onclick="startOrContinueGame()">Click me</button>
<div id="output">Game not started yet.</div>
Upvotes: 0