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

261
Visualizações
How does javascript update the elements in a DOM?

I am trying to slow down an animation of a picture shrinking so that you can actually see it shrink instead of just jump to a smaller size, but what instead happens is that my console log updates as it should-with intervals in-between each update, but the image on the screen waits until the for loop is done and then jumps to the end size instead of gradually getting smaller. Is there something wrong with my code or am I missing some behind the scenes stuff on how the page updates?

function sleep(milliseconds) {
    const date = Date.now();
    let currentDate = null;
    do {
      currentDate = Date.now();
    } while (currentDate - date < milliseconds);
}

function makeSmaller(){
    for (let i = 100; i>50; i--){
    rockButtonImage.style.width = i+'%';
    console.log(rockButtonImage.style.width);
    sleep(50);
    }
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Modern browsers avoid unnecessary renderings of a page and wait while a JavaScript execution iteration is complete before doing a rendition.

The sleep() function in the provided code does not really cause a browser to sleep but rather to do a processor-intensive computation, forbidding the browser from rendering anything.

You can try using the setTimeout() function instead, e.g.:

var i = 100;
function makeSmaller(){
    console.log(rockButtonImage.style.width);
    rockButtonImage.style.width = i+'%';
    i--;
    if (i > 50) {
        setTimeout(makeSmaller, 50);
    }
}

You might also find it useful to rely on CSS animations or CSS transitions instead of JavaScript for such visual effects as JS is not nearly as efficient as they are.

See also:

  • More on setTimeout: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
  • More about the CSS animations: https://developer.mozilla.org/en-US/docs/Web/CSS/animation
about 4 years ago · Juan Pablo Isaza Relatório

0

You have to dynamically get the DOM element getElementById and then change the width. Im not sure in which context the RockButton variable lives. Its all about the state.

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