0

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>
Bilal
  • 3,191
  • 4
  • 21
  • 49
ukulele
  • 79
  • 10
  • It's unclear what you are trying to achieve. When inside the `else` block where you invoke `cancelAnimationFrame`, `increaseHeight` already had been called and there is nothing to cancel any more? – Bergi Nov 16 '19 at 21:31
  • 1
    you always `animate = requestAnimationFrame(increaseHeight);` regardless of condition – Bravo Nov 16 '19 at 21:33
  • FYI [`document.getElementsByClassName('box1')[0]` is just horrible code.](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474) – Scott Marcus Nov 16 '19 at 21:40

2 Answers2

0

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

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.

frodo2975
  • 10,340
  • 3
  • 34
  • 41