javascriptrequestanimationframecancelanimationframe

Why the js window.cancelAnimationFrame() not working?


Code

Not Working :-

let animateFrame ;
function animate (){
    if(animateFrame > 200 ) {
        window.cancelAnimationFrame(animateFrame );
    } 
    console.log(animateFrame ) ;
    animateFrame =  window.requestAnimationFrame(animate);
}
animate()

Working Don't Know Why :-

let animateFrame ;
function animate (){

   animateFrame =  window.requestAnimationFrame(animate);
   if(animateFrame > 200 ) {
        window.cancelAnimationFrame(animateFrame );
   }
   console.log(animateFrame ) ;
}
animate()

It would be great if you explain it through example please .

Thank you for u r time.


Solution

  • In the first example:

    1. If the frame is over 200, you cancel the animation
    2. You log the frame
    3. You start the animation (which makes the cancel pointless)