I have developed a unique twist on the classic Tic Tac Toe game called 'advanced' Tic Tac Toe. In this version, each move made by a player disappears after 10 seconds, returning the square to its original blank state. Everything works smoothly in the game, but there's a challenge when a user chooses to start a new game while canceling the current one.
If a player initiates a new game and clicks on a square that was previously occupied in the previous game, the timeout mechanism clears the square based on the previous game instead of waiting for the full 10 seconds as intended.
The issue lies in using clearTimeout to reset the timer only for the most recent instance of setTimeout - it doesn't account for multiple instances where squares were selected before resetting the game board. Since setTimeout is applied individually to each X and O within an onclick function, it becomes tricky to track multiple instance IDs.
Any insights or suggestions on how to address this issue would be greatly appreciated! See the code snippet below for reference.
UPDATE: A work-in-progress live demo of the game can be accessed here:
Global variables:
var elements = document.getElementsByClassName('cell');
var rows = document.getElementsByClassName('row');
var alternate = 0;
var counter = 0;
var timerX; // Manages setTimeout instances for 'X'
var timerO; // Manages setTimeout instances for 'O'
Function for setting X's and O's:
var play = function() {
for (i = 0; i < elements.length; i++) {
elements[i].onclick = function () {
if (this.className[0] == "c" && win == false) {
if (alternate % 2 == 0) {
this.className = "xmove";
alternate++;
counter++;
var paramPass = this;
timerX = setTimeout(function() {disappear(paramPass);}, 10000) // Maintains ID of the most recent setTimeout instance for 'X'
} else {
this.className = "omove";
alternate++;
counter++;
var paramPass = this;
timerO = setTimeout(function() {disappear(paramPass);}, 10000) // Maintains ID of the most recent setTimeout instance for 'O'
}
}
position(this);
analysis();
}
}
}
Reset function triggered by user selecting 'New Game':
var reset = function() {
header[0].innerHTML = "Tic Tac Toe";
for (i = 0; i < rows.length; i++) {
for (j = 1; j < 6; j += 2) {
rows[i].childNodes[j].className = "cell animated bounceIn";
}
}
clearTimeout(timerX); // Clears Timeout for the most recent instance (last 'X' clicked) before the game was reset
clearTimeout(timerO); // Clears Timeout for the most recent instance (last 'O' clicked) before the game was reset
board = [["","",""],["","",""],["","",""]];
counter = 0;
alternate = 0;
win = false;
}