Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

274
Vistas
Why is my console.log statement running 9 times when the page loads and gives me 0 every time?

I am working on a tic-tac-toe game and i am trying to send an alert when player one has 5 X's on the board resulting in a tie.

Basically player one always goes first and starts with X and if player one's counter hits 5, i want to send an alert. But whenever i console.log p1Counter, i get 0 9 times when the page loads before i even start to play.

<!DOCTYPE html>
<html>
  <head>
    <link rel='stylesheet' href='styles.css'>
    <title>Tic Tac Toe</title>
  </head>
  <body>
    <h1 id='heading'>Tic-Tac-Toe World Championship 2021</h1>
    <div id='game-board'>
      <table>
        <tr>
          <td></td><td></td><td></td>
        </tr>
        <tr>
          <td></td><td></td><td></td>
        </tr>
        <tr>
          <td></td><td></td><td></td>
        </tr>
      </table>
    </div>
    <div id=button-box>
      <button type='button'>Reset!</button>
    </div>
    <script src='app.js'></script>
  </body>
</html>

Here is the javascript code:

document.addEventListener('DOMContentLoaded', function(event) {

  let boxes = document.getElementsByTagName('td');

  let p1Counter = 0;
  let p2Counter = 0;

  for (let i = 0; i < boxes.length; i++) {
    console.log(p1Counter)

    if (p1Counter === 5) {
      window.alert('Tie Game...')
    }

    boxes[i].onclick = elem => {

    if ((elem.target.textContent === 'X') ||
        (elem.target.textContent === 'O')) {
      return;
    }

    if (p1Counter === p2Counter) {
      elem.target.textContent = 'X';
      p1Counter++;
    } else {
      elem.target.textContent = 'O';
      p2Counter++;
    }
   }
  }
});

enter image description here

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Because after onclick assign, it return to new loop and never increase your variable.

boxes[i].onclick = elem => {}

The p1Counter only increase when you click to the td tag, I add some style to display the box to easy to view.

<!DOCTYPE html>
<html>
  <head>
    <link rel='stylesheet' href='styles.css'>
    <title>Tic Tac Toe</title>
    <style>
    table, th, td {
  border: 1px solid black;
  height: 50px;
  width: 200px;
}
    </style>
  </head>
  <body>
    <h1 id='heading'>Tic-Tac-Toe World Championship 2021</h1>
    <div id='game-board'>
      <table>
        <tr>
          <td></td><td></td><td></td>
        </tr>
        <tr>
          <td></td><td></td><td></td>
        </tr>
        <tr>
          <td></td><td></td><td></td>
        </tr>
      </table>
    </div>
    <div id=button-box>
      <button type='button'>Reset!</button>
    </div>
    <script>
    document.addEventListener('DOMContentLoaded', function(event) {

  let boxes = document.getElementsByTagName('td');

  let p1Counter = 0;
  let p2Counter = 0;

  for (let i = 0; i < boxes.length; i++) {
    console.log(p1Counter);
    
    if (p1Counter === 5) {
      window.alert('Tie Game...')
    }

    boxes[i].onclick = elem => {

    if ((elem.target.textContent === 'X') ||
        (elem.target.textContent === 'O')) {
      return;
    }

    if (p1Counter === p2Counter) {
      elem.target.textContent = 'X';
      p1Counter++;
      console.log(p1Counter);
    } else {
      elem.target.textContent = 'O';
      p2Counter++;
      console.log(p2Counter);
    }
   }
  }
});
    </script>
  </body>
</html>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Your for loop only runs 1 time, when your page loads, then the only code that gets run again is the part inside the p1Counter and p2Counter get updated.

And your console.log gets run 9 times due to your loops that gets 9 td elements.

document.addEventListener('DOMContentLoaded', function(event) {

  let boxes = document.getElementsByTagName('td');

  let p1Counter = 0;
  let p2Counter = 0;

  for (let i = 0; i < boxes.length; i++) {
    boxes[i].onclick = elem => {
      if (p1Counter === 5) {
        window.alert('Tie Game...')
      }
      if ((elem.target.textContent === 'X') ||
        (elem.target.textContent === 'O')) {
        return;
      }

      if (p1Counter === p2Counter) {
        elem.target.textContent = 'X';
        p1Counter++;
      } else {
        elem.target.textContent = 'O';
        p2Counter++;
      }
    }
  }
});
td {
  border: 1px solid black;
  padding: 10px;
}
<html>

<head>
  <link rel='stylesheet' href='styles.css'>
  <title>Tic Tac Toe</title>
</head>

<body>
  <h1 id='heading'>Tic-Tac-Toe World Championship 2021</h1>
  <div id='game-board'>
    <table>
      <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
    </table>
  </div>
  <div id=button-box>
    <button type='button'>Reset!</button>
  </div>
</body>

</html>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda