Estoy tratando de aprender bucles while en Javascript. ¿Por qué este ciclo while no se ejecuta incluso cuando se hace clic en el botón y el valor booleano se vuelve verdadero? ¿Es posible que los bucles while reaccionen a los cambios de variables impulsados por eventos?
let run = false; let count = 0; const button = document.getElementById("startstop"); const counter = document.getElementById("counter"); button.addEventListener('click', function() { run = !run; //clever way to toggle the boolean }) while (run == true) { count++; counter.innerHTML = count; } <button id="startstop">Start/Stop</button> <p id="counter">0</p>El bucle no se ejecuta porque run es falso.
Aquí podemos mover el tiempo al botón, pero eso no funcionará porque el ciclo cerrado no le da tiempo al DOM para actualizarse.
button.addEventListener('click', function() { run = !run; //clever way to toggle the boolean while (run) { count++; counter.innerHTML = count; } })NO recomiendo usar bucles while para actualizar DOM
Esto funcionará, pero el ciclo se ejecutará incluso cuando no se actualice el contador.
let run = false; let count = 0; const button = document.getElementById("startstop"); const counter = document.getElementById("counter"); button.addEventListener('click', function() { run = !run; //clever way to toggle the boolean }) setInterval(function() { if (!run) return count++; counter.innerHTML = count; },10) <button id="startstop">Start/Stop</button> <p id="counter">0</p>Una versión más elegante sería clearInterval
let run = false; let count = 0; let tId; const button = document.getElementById("startstop"); const counter = document.getElementById("counter"); button.addEventListener('click', function() { run = !run; //clever way to toggle the boolean if (run) tId = setInterval(function() { count++; counter.innerHTML = count; }, 10) else clearInterval(tId) }) <button id="startstop">Start/Stop</button> <p id="counter">0</p>El while se está ejecutando, pero cuando se carga la página, por lo que cuando hace clic en el botón, el bucle while ya ha pasado. Puede ver esto en acción cuando coloca su bucle while dentro del detector de clics, sin embargo, este no es el comportamiento que desea. En su lugar, use un intervalo para solucionar este problema como se muestra a continuación:
let run = false; let count = 0; let interval = null; const delay = 100; const button = document.getElementById("startstop"); const counter = document.getElementById("counter"); button.addEventListener('click', function() { run = !run; if (run === true) { interval = setInterval(() => { count++; counter.innerHTML = count; }, delay) } else { clearInterval(interval) } }) <button id="startstop">Start/Stop</button> <p id="counter">0</p>Cuando inicia la página, el bucle while termina la primera vez. Al alternar el booleano, no volverá a representar automáticamente el dom por usted. Entonces, si desea ejecutar el ciclo while, deberá envolverlo en una función y llamarlo.
PD Ejecutar este código congelará su navegador por cierto. Intenta agregar un retraso
let run = false; let count = 0; button.addEventListener('click', function() { run = !run; //clever way to toggle the boolean doRun(); }) const doRun = () => { while (run) { count++; counter.innerHTML = count; } } doRun() <button id="startstop">Start/Stop</button> <p id="counter">0</p>