Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!