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

185
Visualizações
How to run a requestAnimationFrame animation for a certain duration?

I have the following function that scrolls some elements "up" out of view by adjusting their style every "tick":

const incr = 1;
let moved = 0;

function changeHeight( children, duration, setTop) {
  // duration = 1500
  const height = children.clientHeight; // in this case, 166px

  let moved = 0; 
  const slideUp = function (timestamp) {
    // we're done if the amount moved is larger than height
    if ( moved < height ) { 
      children.style.top = `${ setTop( moved, height ) }px`;
      moved = moved + incr // move by some amount

      requestAnimationFrame(slideUp) 

    } else {
      // reset
      moved = 0;
    }
  };

  // start sliding
  slideUp();
}

If requestAnimationFrame triggers roughly every 16ms or so, I would like to use duration to dictate how long the animation will be running for, so the formula seems to be height * 16.5 / duration

I'm confused by requestAnimationFrame - why is the time per tick not constant? I'd like to use timestamp that's generated by requestAnimationFrame but the first few cycles take much longer than the average of ~16.5

Is the 16.5 going to look different on a different machine or screen?

How do I make the height change take exactly the amount of time specified?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

What you want is called delta-time. The formula is Math.min((now - start) / duration, 1) * final_amount.

Using this delta-time, you don't need to care at which frequency your interval fires, every step is rendered "where it should be".

As for your questions,

why is the time per tick not constant

Certainly because the browser has a lot of things to do during the first frames and couldn't do everything in the 16.7ms frame. It will thus move your callback to be executed a bit later, and may even skip frames if under too much pressure.

Is the 16.5 going to look different on a different machine or screen?

Yes, requestAnimationFrame will basically try to follow the monitor's refresh rate. So on a 60Hz monitor you'll indeed have 16.7ms per frame, but on a 120Hz monitor you'd have only half of it.

How do I make the height change take exactly the amount of time specified?

Use a delta-time:

const elem = document.querySelector("div");
let moved = 0;
changeHeight(elem, 200, 5000);

function changeHeight(elem, height, duration) {
  const start = performance.now();
  const step = function () {
    const now = performance.now();
    const delta = Math.min((now - start) / duration, 1);
    elem.style.height = (delta * height) + "px";
    if (delta < 1) {
      requestAnimationFrame(step);
    }
  };
  step();
}
div { width: 50px; background: green; }
<div></div>

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