Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda