'How do I start an animation for a certain time?

I have the main loop of the program looped using requestAnimationFrame As for example after the character crashed, disable the collision for him for 3 seconds and blink at the same speed? At the same time, the entire gameplay will continue to animate at a different speed

How can I run another animation at a different speed and for a time during one animation?

The code I think is not required here, a standard animation loop using requestAnimationFrame:

function loop() {
    requestAnimationFrame(loop)

    let now = new Date().getTime(),
        dt = now - (time || now)

    time = now

    game.step(dt)
    game.render()
}

thanks



Solution 1:[1]

You'll need store "timers" for each animation separately, then add conditions that would trigger certain animations (is character crashed? -> animate1, if animate1 is currently running -> animate2, etc)

const animationTimers = {
  animation1:
  {
    time: 200, //wait between frames
    timer: 0, //this will hold previous frame timestamp
    func: animationFunc1 //callback function
  },
  animation2:
  {
    time: 500,
    timer: 0,
    func: animationFunc2
  }
};
function loop(timestamp)
{
  if (timestamp < 6000) //limit whole animation to 6 sec
    requestAnimationFrame(loop)

  let now = new Date().getTime();
  for(let i in animationTimers)
  {
    if (now - animationTimers[i].timer > animationTimers[i].time)
    {
      animationTimers[i].timer = now;
      animationTimers[i].func();
    }
  }
}

loop(0);

function animationFunc1()
{
  if (animationTimers.animation2.timer)
  {
    if (!animationTimers.animation1.started)
      animationTimers.animation1.started = animationTimers.animation1.timer; //remember when started

    if (new Date().getTime() - animationTimers.animation1.started < 4000) //only animate for 4 sec
      console.log("animation 1", "remaining", (4000-(new Date().getTime() - animationTimers.animation1.started)) / 1000, "sec");
  }
}

function animationFunc2()
{
  console.log("animation 2");
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vanowm