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

171
Visualizações
Using the modulo operator to get an infinite loop around an array

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);   
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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)

about 4 years ago · Juan Pablo Isaza Relatório

0

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;
    white-space: pre;
    font-family: monospace;
    padding: 10px;
}
<html>
<body>
    <div id="mod"></div>
</body>

</html>

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