Why does it print out all elements following the "if statement" instead of just one element?

I am currently working on creating a Tic Tac Toe game using JavaScript, and I want to log all the elements that do not have a URL assigned to them yet. However, when I try to implement this, it logs all elements including those that already have a URL. I am wondering why this is happening.

const cells = document.querySelectorAll("img");
let boxes = [];
cells.forEach(function (cell) {
  cell.addEventListener("click", playerChoice, false);
});
function playerChoice() {
  this.src = "Small_uppercase_letter_X.svg.png";

  setTimeout(1000, computerChoice());
}
function computerChoice() {
  for (let cell of cells) {
    if (cell.src != "Small_uppercase_letter_X.svg.png") {
      console.log(cell);
    }
  }
}

Answer №1

Your code is experiencing an issue due to the incorrect usage of the setTimeout function. This results in the computerChoice function being called immediately after placing the "X" image in the clicked cell. To resolve this, it is important to pass a function to setTimeout as shown below:

Take a look at this revised solution:

    const cells = document.querySelectorAll("img");
let boxs = [];
cells.forEach(function (cell) {
  cell.addEventListener("click", manChoice, false);
});
function manChoice() {
  if (this.src !== "Small_uppercase_letter_X.svg.png") {
    this.src = "Small_uppercase_letter_X.svg.png";
    setTimeout(function() {
      computerChoice();
    }, 1000);
  }
}
function computerChoice() {
  const availableCells = Array.from(cells).filter(cell => cell.src !== "Small_uppercase_letter_X.svg.png");
  if (availableCells.length > 0) {
    const randomIndex = Math.floor(Math.random() * availableCells.length);
    const chosenCell = availableCells[randomIndex];
    chosenCell.src = "Small_uppercase_letter_O.svg.png";
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Identify the parent container in jQuery and exclude any click events triggered by child input checkboxes

In my jQuery Mobile application, I have a piece of jQuery code that selects the child checkbox when a li is clicked. While this functionality works well, it interferes with the default behavior of the checkbox itself, making it impossible to deselect the c ...

Exclude certain APIs from utilizing basic authentication in Fastify

I currently have two APIs set up: /auth and /no-auth. My goal is to only use basic authentication for one of them. To implement this, I am using the fastify-basic-auth plugin with fastify in a node environment. The /auth route should require authenticat ...

The program crashed after attempting to write a char** into a file and resulted in a core

I am encountering an issue with accessing a char ** in one of my structs. uint64_t id; struct timing timing; //command *command; uint32_t argc; char ** argv; } taskR; I have stored everything correctly in my struct, however when trying ...

EJS not displaying object values properly

I'm currently in the process of setting up a blog and I want to create a page that displays the titles of all the articles I've written. For example: List of Articles: * Title: Article 1 * Title: Article 2 * Title: Article 3 Below is my Schem ...

Navigate through the website by transforming the arrow and clicking the link

I am struggling with transitioning my arrow from › (right) to ˇ (down) when toggled. I can't figure out where to place it. If you look at Menu 1 > Submenu 1 > Text with hyperlink I want the 'Text with Hyperlink' to be clickable on ...

Having difficulty locating the value in the input search field

I am attempting to customize my search bar so that it automatically includes wildcards on both ends when a user performs a search. Although the code below almost does what I want by adding the wildcards on both sides, it adds them to an empty search term ...

Having trouble making an AJAX request work in AngularJS?

Just dipped my toes into the world of Angular (only a few hours in). Managed to tweak the demo to get close to what I need, but hitting a roadblock with my AJAX request. After trying a variety of fixes, one puts me in an endless loop (discovered that&apos ...

How to build a registration form with Stateless Components?

Could someone provide a sample code or explanation on how to create a form using stateless components? I'm also in need of a Material UI form example that utilizes refs. Please note that I am working with Material UI components. Below is the curren ...

Check if two associative arrays contain identical elements

I need to create a PHP function that checks if two arrays are identical and returns true. For example: assertArrayEquals(array('a'=>1, 'b'=>2), array('a'=>1, 'b'=>2)); // True assertArrayEquals(array(&a ...

How to use jQuery to dynamically add a variable to a request in Laravel 5.2

Is it feasible to append a variable to the Laravel cookie in the client using jQuery? Understandably, the Cookie is linked to the request during GET? Can you include a variable in the $request container in Laravel 5.2 using jQuery before initiating a GET ...

Converting PHP date format to JavaScript date format

I'm struggling to solve this problem $datetime = new Date().toLocaleString(); // returns current date in format 10/21/2021, 14:29:43 How can I generate the desired date format using JavaScript? The output should look like this: 2021-10-21 16:30:01 ...

Having trouble retrieving data from the table with AJAX and CodeIgniter

I am currently developing a comprehensive HRM+CRM system (Human Resource Management and Customer Relation Management). I have encountered an issue while trying to generate an invoice for each customer. I am struggling to resolve this problem and would appr ...

Tips for effectively separating HTML and JavaScript for a cleaner code structure

Is it necessary and worth it to decouple HTML and JavaScript? In JavaScript logic, you always have to use some HTML elements... I know that in C#, you can decouple for easier maintenance and testing scenarios. ...

What is the correct method for adjusting the height properties of an element?

I'm trying to adjust the height of my div using the code below var heightMainDiv = window.innerHeight - 50; var myDiv = $("#main_content")[0]; myDiv.clientHeight = heightMainDiv; myDiv.scrollHeight = heightMainDiv; However, the values of clientHeigh ...

Troubleshooting React and Material-UI: Adjusting <slider> component for use with personalized data

I am facing a challenge with using the Material-UI slider to showcase API data. The unique aspect here is that the slider is intended for displaying data without any interactivity. Encountering an error message: Slider.js:91 Uncaught TypeError: nearest.to ...

Tips for concealing title when window is resized?

I'm working on a webpage that has a title at the top, but I want to hide it on smaller devices and make it responsive when the window is resized. Currently, I only show the title when the window width (w) is greater than 450 pixels. However, I'm ...

What steps do I need to take in order to develop a custom interactive analyzer game using html/css

Hello there, I am on a mission to develop a mobile-friendly version of an analyzer game that I came across on this link - . The current version of the game is built using flash. My goal is to be able to easily customize the colors and images to fit differ ...

Navigating specific elements within ReactORTraversing designated components

Trying to iterate through specific elements in React to render a portion of an array for each view. The rendering of the array should start from ArrayIndexStart and end at ArrayIndexEnd. Here is the current implementation: const ObjectArray = [ {" ...

What is the PHP function to combine strings with matching indexes in an array?

Hey there, so I've got this code snippet that does the job... $Array1 = array("Hello, ", "foo", "The quick brown fox jumped "); $Array2 = array("World!", "bar", "the lazy dog."); $Array3 = array(); for($x = 0; $x < count($Array1); $x++) { $Arr ...

Adjust the color of the text based on a conditional in react

I am looking for a way to select elements and change text color in my unordered list based on specific conditions. Below is an example of the structure I have: <div style={styles.passwordRules}> <ul style={styles.listOne}> <li style={ ...