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

345
Vistas
Why doesn't setInterval work properly to change an element's color?

I have created a function addElements() which changes an image, background color of the body and text color of a p tag. Now when I run the following code, the image changes at the setInterval infinetely but the colors do not change even once.

function addElements() {
  var img = document.getElementById('img');
  var image = images[Math.floor(Math.random() * images.length)];
  img.src = image;

  var name = document.getElementById('name');
  var color = colors = colors[Math.floor(Math.random() * colors.length)];
  document.body.style.backgroundColor = color;
  name.setAttribute('color', color);
};

window.addEventListener('load', setInterval(addElements, 4321));
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

It seems that the line

var color = colors = colors[Math.floor(Math.random() * colors.length)];

contains an error. You should remove = colors

so that the line is

var color = colors[Math.floor(Math.random() * colors.length)];
about 4 years ago · Juan Pablo Isaza Denunciar

0

instead of name.setAttribute('color', color);

use

name.style.color = color;
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