ukulele
ukulele

Reputation: 97

Why cancelAnimationFrame doesn't cancel the requestAnimationFrame?

I can't figure out why the cancelAnimationFrame method does not cancel the requestAnimationFrame. The console still logs the message. Can anyone provide an explanation?

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="Interaktywny poradnik szybkiego startu dla Brackets.">
    <link rel="stylesheet" href="test.css">

  </head>
  <body>

<div class="box1" style="height:100px;width:100px;background:red">
</div>

</body>

<script>

let container;
container = document.getElementsByClassName('box1')[0];
let increase=0
let animate;
         function increaseHeight(){
                    increase = increase + 2;
                    container.style.height=increase + "px";
          if(increase>200){
            console.log("cancelAnimation");
          cancelAnimationFrame(animate)
          }
      animate = requestAnimationFrame(increaseHeight);
        }
    increaseHeight();
</script>

</html>

Upvotes: 1

Views: 976

Answers (2)

frodo2975
frodo2975

Reputation: 11783

It's not cancelling because you're requesting a new frame after you cancel the one that's already run. You need to put your new frame request inside the if(increase<200){ block. Also, you actually shouldn't be cancelling anything. An animation frame request only runs once, then if you want to run another, you have to request another. So, when your animation is done, just don't request another one, and you'll be good.

Upvotes: 0

Bergi
Bergi

Reputation: 665555

I think what you really want to do is

const container = document.getElementsByClassName('box1')[0];
let increase = 0;
function increaseHeight() {
    if (increase < 200) {
        increase = increase + 2;
        container.style.height = increase + "px";
        requestAnimationFrame(increaseHeight); // continue animation
    } else {
        console.log("stopping animation");
    }
}
increaseHeight();

No cancellation necessary.

Upvotes: 0

Related Questions