Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

340
Views
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 answers
Answer question

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 Report

0

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

use

name.style.color = color;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!