How to create an Animation in Javascript using For

Asked

Viewed 102 times

0

I’m trying to make a Div have the background changed to the three primary colors in case Yellow, Blue and Red, however would only start to change the color 4 seconds after the page is updated, wrote a function that is called 4 seconds after the page refresh, but the colors do not change, in fact it ignores the first colors and jumps right to the last, and does not occur the animation effect, simply turns red, follows down the code...

<script>
    var d = window.document.querySelector('div#msg');

    setTimeout(mudarCor, 4000);


    function mudarCor(){  
        var contador =0;
        while(contador <= 9){

            d.style.background = 'yellow';

            d.style.background = 'blue';

            d.style.background = 'red';
            contador +=1;
        }
     }

</script>

I want you to change between the 3 colors, to show the colors changing on the screen, but I need it to be with the repeat structure for or while, because maybe I need to keep this running endlessly kkk.

2 answers

3


To make animation in Javascript, with modern browsers, one must use the method window.requestAnimationFrame() which informs the browser that an animation is desired and asks the browser to call a specific function to update an animation frame before the next repeat.

The method has as argument a callback that will be invoked before the repintura. In turn the callback has a single argument a DOMHighResTimeStamp, indicating the time at which the callback was lined up by requestAnimationFrame().

The number of callbacks invoked is usually in the order of 60 calls per second, but usually the display update rate is tracked in most browsers, as recommended by W3C.

In this example is created an animation that starts after 4s and changes the colors of a <div>.

var inicio = null; //inicio da animação
var cores = ['yellow', 'blue', 'red']; //Array de cores 
let elem = document.getElementById("colorido");

requestAnimationFrame(mudarCor);

function mudarCor(tempo) {

  if (!inicio) inicio = tempo;

  // Aguarda 4s antes de iniciar a animação
  if ((tempo - inicio) > 4000) {
    //Escolhe uma cor "aleatoriamente" e muda a atual
    elem.style.background = cores[Math.floor(Math.random() * cores.length)];
  }

  //Faz a requisição do próximo quadro
  requestAnimationFrame(mudarCor);
}
#colorido {
  width: 100px;
  height: 100px;
  background: red;
}
<h4>Aviso!!!</h4><span>Se você sofre com epilepsia ou fotossensibilidade não veja esse exemplo</span>
<div id="colorido"></div>

If you want a less intense effect just make the changes at a lower frequency

var inicio = null; //inicio da animação
var ultima = null; // momento da última atualização
var cores = ['yellow', 'blue', 'red']; //Array de cores 
let elem = document.getElementById("colorido");

requestAnimationFrame(mudarCor);

function mudarCor(tempo) {

  if (!inicio) {
    inicio = tempo;
    ultima = tempo;
  }

  // Aguarda 4s antes de iniciar a animação
  if ((tempo - inicio) > 4000) {
    // Só troca a cor a cada 0,5s
    if (tempo - ultima > 500) {
      //Escolhe uma cor "aleatoriamente" e muda a atual
      elem.style.background = cores[Math.floor(Math.random() * cores.length)];
      ultima = tempo;
    }

  }

  //Faz a requisição do próximo quadro
  requestAnimationFrame(mudarCor);
}
#colorido {
  width: 100px;
  height: 100px;
  background: red;
}
<h4>Aviso!!!</h4><span>Se você sofre com epilepsia ou fotossensibilidade não veja esse exemplo</span>
<div id="colorido"></div>

1

In this case, for the color to be changed within a time interval, the ideal is to use the setInterval() instead of the setTimeout(), because he will be executed repeatedly.

Example using the setInterval():

<script>
    var d = window.document.querySelector('div#msg');
    var arrayCores = ['yellow','blue','red'];
    var corAtual = -1;

    function mudarCor() {
        corAtual = (corAtual < arrayCores.length ? (corAtual + 1) : 0);

        d.style.background = arrayCores[corAtual];
    }

    setInterval(mudarCor, 4000);
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.