0

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>
Jakub.Novotny
  • 2,912
  • 2
  • 6
  • 21
  • 1
    You might want to use `setInterval` instead of `setTimeout ` in your case. Check out this fiddle https://jsfiddle.net/wamosjk/v4dqegkx/ – Steve K Oct 25 '21 at 20:21
  • 1
    There's no need to have a separate loop. [You can just move the timeout into the `changeColor` function](https://jsfiddle.net/rb9ue1ch/) and then use it to call the function until the index reaches 360. – Andy Oct 25 '21 at 20:38
  • @SteveK this is really cool, thanks. It worked like a charm. – Jakub.Novotny Oct 25 '21 at 20:48
  • @Andy you are absolutely right. I was not aware it can be rewritten the way you did. – Jakub.Novotny Oct 25 '21 at 20:50

1 Answers1

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

Azizov
  • 1
  • I am afraid your answer does not seem to be working. It does what the original code does, i.e. it runs the loop at once, without any delay in execution. Appreciate the effort, though. – Jakub.Novotny Oct 25 '21 at 20:52