Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

179
Visualizações
Why will this while-loop not run?

I'm trying to learn while-loops in Javascript. Why won't this while loop run even when the button is clicked and the boolean becomes true? Is it even possible to have while-loops react to event-driven variable changes?

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>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The loop is not executed because run is false.

Here we can move the while to the button but that will not work because the tight loop does not give the DOM time to update.

button.addEventListener('click', function() {
  run = !run; //clever way to toggle the boolean
  while (run) {
    count++;
    counter.innerHTML = count;
  }
})

I do NOT recommend to use while loops at all to update DOM

This will work but the loop will run even when not updating the counter

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>

A more elegant version would be to 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>

about 4 years ago · Juan Pablo Isaza Relatório

0

The while is running but when the page loads, so when you click on the button the while loop has already passed. You can see this in action when you place your while loop inside the click listener, however this is not the behaviour you want. Instead use an interval to fix this issue like shown below:

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

When you start up the page, the while loop actually ends the first time. When toggling the boolean, it will not automatically rerender the dom for you. So if you want to run the while loop, you'll need to wrap it in a function and call it.

PS Running this code will freeze your browser btw. Try adding in a delay

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda