skip to Main Content

I am trying to loop this block of code. How do I do that? I am trying to change the color forever.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Home</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width" />
    <link rel="stylesheet" href="styles.css" />
    <script  defer  src="script.js"></script>
  </head>
  <body>
    <h1 onclick="changecolor()">HackerXGames</h1>
  </body>
</html>
function changecolor(){
  setTimeout(() => {
    document.body.style.backgroundColor = "blue";
    setTimeout(() => {
      document.body.style.backgroundColor = "red";
      setTimeout(() => {
        document.body.style.backgroundColor = "lightblue";
        setTimeout(() => {
          document.body.style.backgroundColor = "#800000";
          setTimeout(() => {
            document.body.style.backgroundColor = "#ff0066";
            setTimeout(() => {
              document.body.style.backgroundColor = "#ff6699";
              setTimeout(() => {
                document.body.style.backgroundColor = "#9900cc";
                setTimeout(() => {
                  document.body.style.backgroundColor = "Lime";
                  setTimeout(() => {
                    document.body.style.backgroundColor = "#000099";
                    setTimeout(() => {
                      document.body.style.backgroundColor = "#ff9430";
                     },1500)
                   },1500)
                 },1500)
               },1500)
             },1500)
           },1500)
         },1500)
       },1500)
     },1500)

   },2500)
  }

2

Answers


  1. Maybe try something like this.

    // keep a list of all the colors you want to cycle through
    const colors = [
        'blue',
        'red',
        'lightblue',
        '#800000',
        '#ff0066',
        '#ff6699',
        '#9900cc',
        'Lime',
        '#000099',
        '#ff9430',
    ];
    
    // this function sets the color
    const changeColor = (color) => {
        document.body.style.backgroundColor = color;
    };
    
    // keep track of the color you are on
    let colorIndex = 0;
    
    // this function waits for an amount of milliseconds
    const sleep = async (millis) => {
        return new Promise((resolve) => {
            setTimeout(resolve, millis);
        });
    };
    
    // main function
    (async () => {
        // loop forever
        while (true) {
            // sleep for 1500 ms
            await sleep(1500);
            // change the color
            changeColor(colors[colorIndex]);
            // update the color index
            colorIndex = (colorIndex + 1) % colors.length;
        }
    })().catch(console.error);
    
    Login or Signup to reply.
  2. Use setInterval if you want something to loop endlessly at a continuous rate.

    The function returns an ID for the interval, so if you want to stop it at a later time, you can call clearInterval with that ID.

    const colors = [
        'blue',
        'red',
        'lightblue',
        '#800000',
        '#ff0066',
        '#ff6699',
        '#9900cc',
        'Lime',
        '#000099',
        '#ff9430',
    ];
    
    let colorInterval;
    let colorIndex = 0;
    
    function startChangingBg() {
        changeBackground(); // This is optional; so you don't have to wait for first interval
        
        colorInterval = setInterval(changeBackground, 1500);
    }
    
    function stopChangingBg() {
        clearInterval(colorInterval);
    }
    
    function changeBackground() {
        document.body.style.backgroundColor = colors[colorIndex];
        colorIndex += 1;
        if (colorIndex >= colors.length) {
          colorIndex = 0;
        }
    }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title>Home</title>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width" />
        <link rel="stylesheet" href="styles.css" />
        <script  defer  src="script.js"></script>
      </head>
      <body>
        <h1>HackerXGames</h1>
        <button onclick="startChangingBg()">Start changing background</button>
        <button onclick="stopChangingBg()">Stop changing background</button>
      </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search