Home > database >  Using the modulo operator to get an infinite loop around an array
Using the modulo operator to get an infinite loop around an array

Time:03-11

I'm able to come up with simple codes using the modulo operator and I understand it on an abstract level, but I'm having trouble seeing the concept/idea on the actual code. Can anyone explain it to me using this simple version I did for an infinite loop to change the background? I would really appreciate some help. This and recursion are really giving me a hard time. I simply can't see what they do when I read the code

let i = 0;

function mud() {
  const doc = document.body;
  let colour = ["#5FA4FF", "#5DA3FF", "#02C2F1", "#2982F8"];
  doc.style.backgroundColor = colour[i];
  i = (i   1) % colour.length;
}
setInterval(mud, 2000);   

CodePudding user response:

The % is taking the remainder of division. Here's an interactive example based on your code. The variables are added to the div so you can watch their values change with the color.

var mod = document.querySelector("#mod");
    let i = 0;

    function mud() {
        let colour = ["#5FA4FF", "#5DA3FF", "#02C2F1", "#2982F8"];
        mod.style.backgroundColor = colour[i];
    let dividend = (i   1);
    
    //get the remainder of dividend (i 1) divided by color.length (4)
          i =  dividend % colour.length;
        mod.innerText = JSON.stringify({
      dividend,
            divisor: colour.length,
            remainder:i,
            colorHex: colour[i]
        }, null, 2);
    }
    setInterval(mud, 2000);
div {
        width: 200px;
        height: 200px;
        background-color: lightblue;
    }
<html>
<body>
    <div id="mod"></div>
</body>

</html>

CodePudding user response:

Exactly in this code it works as infinite loop because % colour.length always will give a number which less than colour.length and when you add 1 you just go around from 0 to colour.length (not inclusive)

  • Related