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

218
Visualizações
Why doesn't the background color change first?

'use strict';

const sum = num => {
  let acc = 0;
  while (num) {
    acc = acc + num;
    num = num - 1;
  }
  return acc;
};

new Promise((res, reject) => {
  document.querySelector('body').style.backgroundColor = 'red';
  res();
}).then(() => {
  const res = sum(1000000000);
  console.log(res);
});

I want to change the bgcolor to red first and get result of the sum function.

But it's not working well.

After receiving the sum result, change the bg color.

what i missed?

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

0

I believe the code is working correctly. However, after setting the background color, you immediately lock up the processor with an extremely long loop. The browser does not have time to color the background before it gets frozen calculating the sum of 1 to a billion. While the property of the background color will be set before the function, the actual re-rendering takes a non-zero amount of time.

You can see this by setting a delay before letting the promise return. In this case (or at least on my processor anyway), the background will turn red first.

'use strict';

const sum = num => {
  let acc = 0;
  while (num) {
    acc = acc + num;
    num = num - 1;
  }
  return acc;
};

new Promise((res, reject) => {
  document.querySelector('body').style.backgroundColor = 'red';
  setTimeout(res, 250);
}).then(() => {
  const res = sum(1000000000);
  console.log(res);
});

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