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

211
Visualizações
Why aren't the images getting changed every 2 seconds?
let i = 0;

function change() {
  if (i < res.length) document.getElementById("cont").style.backgroundImage = `url(static/letters/${res[i++]}.jpg)`;
}
window.onload = function() {
  setInterval(change, 2000);
};

I want this change only once till all the images get displayed and then want the container empty. What's wrong with my code?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can check this implementation

let i = 0;

let interval //the variable to keep the current interval

//simulate your `res` data 
const res = [
  "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg",
  "https://images.unsplash.com/photo-1612151855475-877969f4a6cc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8aGQlMjBpbWFnZXxlbnwwfHwwfHw%3D&w=1000&q=80",
  "https://www.w3schools.com/w3css/img_lights.jpg"
]

function change() {
  if (i < res.length) {
    document.getElementById("cont").style.backgroundImage = `url(${res[i++]})`;
  } else {
    document.getElementById("cont").style.backgroundImage = "none";
    clearInterval(interval); //remove the current interval after finish the loop
    i = 0; //reset index value
  }

}
window.onload = function() {
  interval = setInterval(change, 2000); //set the current interval
};
#cont {
  height: 300px;
  width: 300px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 300px 300px;
  transition: 0.2s;
}
<div id="cont"></div>

about 4 years ago · Santiago Trujillo Relatório

0

This might do the job :

if (i < res.length) document.getElementById("cont").style.backgroundImage = `url('static/letters/${res[i++]}.jpg')`;
about 4 years ago · Santiago Trujillo 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