1

Tengo un botón que inicia un setTimeout cada vez que lo pulso (no debería ser así, solo podría estar activo uno a la vez, pero bueno).

Imaginemos que tengo 3 setTimeout abiertos y quiero pararlos todos a la vez, intenté hacer un botón dinámico que los parase, y una vez parados, se borrase. Crear el botón una sola vez fue fácil, lo difícil, y que no me sale, es parar todos los procesos de una.

El código es este:

window.addEventListener('load', ()=>{

  document.querySelector('.magic').addEventListener('click', ()=>{
    //creamos un boton para parar el ciclo
    let stop_btn = createStopBtn();
    if(!document.querySelector('.stop-btn')){
      document.body.appendChild(stop_btn);
    }
    var timer = false;
    startGame(stop_btn, timer);
  })
});

function startGame(stop_btn, timer){
  //obtener eel boton
  if(document.querySelector('.stop-btn') == null){
    console.log('timer has stopped');
    clearTimeout(timer);
  }
  else{
    document.querySelector('.stop-btn').onclick = function(){
      clearTimeout(timer);
      document.querySelector('.stop-btn').remove();
  }}
  //obtenemos un length
  let lng = document.querySelectorAll('.cont').length;
  //elegimos aleatoriamente un número entre 0 y el lenght
  let rng = randomNumber(lng);
  //obtenemos el cuadrado que queremos
  let dvc = getDivColored(rng);
  console.log(rng);

  if(dvc.style.backgroundColor == dvc.getAttribute('data')){
    dvc.style.backgroundColor = 'white';
  }
  else{
    dvc.style.backgroundColor = dvc.getAttribute('data');
  }

  timer = setTimeout(startGame, 1000);
}

function randomNumber(lng){
  return Math.floor(Math.random() * Math.floor(lng));
}

function getDivColored(rng){
  return document.querySelectorAll('.cont')[rng];
}

function createStopBtn(){
  let btn = document.createElement('button');
      btn.type='button';
      btn.innerHTML='STOP';
      btn.className='stop-btn'

  return btn
}
.cont{
    width:50px;
    height:50px;
    border:1px solid #000;
    margin:0 15px;
    display: inline-block;
    float: left;
}

.red{
    background: red;
}
.blu{
    background: blue;
}
.yel{
    background: yellow;
}
.gre{
    background: green;
}
.pur{
    background: purple;
}
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
    <title>013 : paleta</title>
    <link rel="stylesheet" type="text/css" href="css/013.css">
    <script src="js/013.js"></script>
</head>
<body>
    <div class="plt">
        <div class="red cont" data="red"></div>
        <div class="blu cont" data="blue"></div>
        <div class="yel cont" data="yellow"></div>
        <div class="gre cont" data="green"></div>
        <div class="pur cont" data="purple"></div>
    </div>
<button type="button" class="magic">MAGIA</button>
</body>
</html>

Como ven, si pulsamos dos veces al start se crean dos procesos simultáneos, y el botón stop solo puede llegar a parar uno.

Se que podría hacer el botón de start dinámico, y borrarlo cuando lo pulse. PERO, quiero aprender a hacer lo otro antes :3

¿Cómo podía hacerlo?


[EDIT]

Intentando implementar el array con los setTimeout de @Pablo Lozano, creo que la he liado un poco más...

Ahora mismo lo tengo así:

window.addEventListener('load', ()=>{

  document.querySelectorAll('.cont').forEach(item=>{
    item.addEventListener('click', (item)=>{
      let col = getColor(item.target);
      changeCol(col);
    });
  });

  document.querySelector('.magic').addEventListener('click', ()=>{
    //creamos un boton para parar el ciclo
    let stop_btn = createStopBtn();
    if(!document.querySelector('.stop-btn')){
      document.body.appendChild(stop_btn);
    }
    //var timer;
    startGame(stop_btn);
  })
});

function getColor(item){
  return item.getAttribute('data');
}

function changeCol(col){
  if(document.body.style.backgroundColor != col){
    document.body.style.backgroundColor = col;
  }
  else{
    document.body.style.backgroundColor = 'white';
  }
}

function startGame(stop_btn){

    var timeouts= [];

    document.querySelector('.stop-btn').onclick = function(){
      while(timeouts.length){
        clearTimeout(timeouts.pop());
      }
    document.querySelector('.stop-btn').remove();
    }
        //obtenemos un length
  let lng = document.querySelectorAll('.cont').length;

  //elegimos aleatoriamente un número entre 0 y el lenght
  let rng = randomNumber(lng);

  //obtenemos el cuadrado que queremos
  let dvc = getDivColored(rng);

  //obtenemos data
  let data = dvc.getAttribute('data');

  //comprobamos selectores
  if(dvc.classList.contains(data)){
    dvc.classList.remove(data);
    dvc.classList.add('white');
  }
  else{
    dvc.classList.remove('white');
    dvc.classList.add(data);
  }

  //setTimeout activo
  //timer = setTimeout(startGame, 1000);
  timeouts.push(setTimeout(() => startGame(timeouts.length+1),1000));
}

function randomNumber(lng){
  return Math.floor(Math.random() * Math.floor(lng));
}

function getDivColored(rng){
  return document.querySelectorAll('.cont')[rng];
}



function createStopBtn(){
  let btn = document.createElement('button');
      btn.type='button';
      btn.innerHTML='STOP';
      btn.className='stop-btn'

  return btn
}
.cont{
    width:50px;
    height:50px;
    border:1px solid #000;
    margin:0 15px;
    display: inline-block;
    float: left;
}

.red{
    background-color: red;
}
.blue{
    background-color: blue;
}
.yellow{
    background-color: yellow;
}
.green{
    background-color: green;
}
.purple{
    background-color: purple;
}
.white {
    background-color: white;
}
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<head>
    <title>013 : paleta</title>
    <link rel="stylesheet" type="text/css" href="css/013.css">
    <script src="js/013.js"></script>
</head>
<body>
    <div class="plt">
        <div class="red cont" data="red"></div>
        <div class="blue cont" data="blue"></div>
        <div class="yellow cont" data="yellow"></div>
        <div class="green cont" data="green"></div>
        <div class="purple cont" data="purple"></div>
    </div>
<button type="button" class="magic">MAGIA</button>
</body>
</html>

Meto los timeout dentro del array tal y como me explicó Pablo, pero a la hora de hacer un borrado universal de los mismos, si no detecta el botón, no lo hace.

Esto me dio para pensar que con un if (!boton) podría controlarlo, y si no lo detecta, haga el delete igualmente. Pero no funcionó.

¿Qué puedo hacer?

1 respuesta 1

1

Si vas a tener un número indeterminado de "timeouts" en cola, puedes usar un array para guardar los identificadores:

let addBtn = document.querySelector("#addTimeout");
let cancelBtn = document.querySelector("#cancel");
let timeouts = [];
addBtn.addEventListener("click", () => {
  timeouts.push(setTimeout(() => writeMessage(timeouts.length + 1), 5000));
});

cancelBtn.addEventListener("click", () => {
  console.log("cancelando", timeouts.length, "ejecuciones pendientes")
  while (timeouts.length) {
     clearTimeout(timeouts.pop());
  }
});

function writeMessage(num) {
  document.querySelector("pre").innerHTML += `Mensaje número ${num}\n`;
  timeouts.shift();//Quito el id, ya se completó
}
  
<button id="addTimeout"> Muestra un mensaje en 5 segundos </button>
<button id="cancel"> Cancela todas las colas </button>
<pre>
</pre>

1
  • Enseguida lo intento implementar en mi código. Muchas gracias
    – AQMR
    el 25 mar. 2021 a las 10:46

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.