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

222
Visualizações
Change background color in a JavaScript loop with delayed display

I wanted to explore CSS hsl colors. The attribute hue from hsl can be between 0 and 360 so I looped through numbers from 0 to 360 and set background color like this hsl(i, 50%, 50%). In order to see the colors, I tried to implement a delayed execution of the code because otherwise I think the code execution would be so fast I could not see it. For some reason, it does not seem to be working. My expectation was to see the color changing every 1 second, but it only changes to red once, and then nothing happens. Moreover, the code runs all at once without the delay. Here is my code:

function myLoop() {
  for (let i = 0; i < 361; i++) {
    console.log(i);
    setTimeout(changeColor(i), 1000);
  }
}

function changeColor(hueIndex) {
  let elem = document.getElementById('bodyId');
  elem.style.backgroundColor = `hsl(${hueIndex}, 50%, 50%)`;
}
<body id='bodyId'>
  <button onclick="myLoop();">Click me!</button>
</body>

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

0

 function myLoop() {
        for (var i = 1; i <= 360; i++) {
            (function (i) {
                setTimeout(function () {
                    document.querySelector("#bodyId").style.backgroundColor = `hsl(${i}, 50%, 50%)`;
                },100);
            })(i)
        }
    }

Function With setTiomeOut

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