I'm working on a Xs and Os game and want to add a countdown timer for each move. The idea is to give players 10 seconds to make their move. How can I create a timer that runs in the background, resets after each move, and ends the game if a player doesn't move in time?
Here's a basic setup of my game board:
```html
<div id="game-container">
<div class="row">
<div class="cell" id="c1"></div>
<div class="cell" id="c2"></div>
<div class="cell" id="c3"></div>
</div>
<div class="row">
<div class="cell" id="c4"></div>
<div class="cell" id="c5"></div>
<div class="cell" id="c6"></div>
</div>
<div class="row">
<div class="cell" id="c7"></div>
<div class="cell" id="c8"></div>
<div class="cell" id="c9"></div>
</div>
</div>
And here’s my current JavaScript:
let currentPlayer = 'X';
let gameActive = true;
function handleCellClick(clickedCell) {
if (clickedCell.textContent === '' && gameActive) {
clickedCell.textContent = currentPlayer;
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
}
}
document.querySelectorAll('.cell').forEach(cell => {
cell.addEventListener('click', () => handleCellClick(cell));
});
How can I add a timer to this setup? Any help would be great!
This implementation should integrate well with your existing code. You might also consider adding a visual countdown display to enhance the user experience.
hey man, i got a cool trick for ya. use setinterval() to run a function every second that updates the timer. then use clearinterval() to stop it when someone makes a move. something like this:
let timer = 10;
let countdown = setinterval(() => {
timer--;
if (timer == 0) {
// end game
clearinterval(countdown);
}
}, 1000);
reset timer to 10 after each move. hope that helps!
Finally, I started the timer when the game begins:
timerId = setInterval(updateTimer, 1000);
This setup worked well for me. The timer resets after each move, and if it reaches zero, the game ends. You might want to add a visual timer display too. Hope this helps!