0

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
S B RAKESH RATH
  • 443
  • 3
  • 10
  • pls format code – Nur Apr 28 '21 at 15:29
  • done, please explain :) – S B RAKESH RATH Apr 28 '21 at 15:37
  • 1
    It's rather odd to use ids returned by the frame as a counter... use a separate variable or you'll run into weird bugs if other parts of the page make calls to the animation frame API. Seems like an [XY problem](https://meta.stackexchange.com/a/233676/399876)... Please describe what "working" means. BTW, this is tagged recursion but there's no recursion here. – ggorlen Apr 28 '21 at 16:05
  • Do not use the id, you can't be sure to be the only one calling rAF. Even internal APIs from the browser may use it some day and your code would break. As for the issue, it's just **always useless** to call `cancelAnimationFrame` in the rAF callback. It already did fire, since you are in. Instead just don't call rAF again instead. – Kaiido Apr 28 '21 at 22:54

1 Answers1

2

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)
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • but why the animateFrame never goes down than 200 , it is always increasing. – S B RAKESH RATH Apr 28 '21 at 15:53
  • @MixUp — When generating unique IDs for something, it is normal to count upwards and not downwards. If you went down you'd quickly hit 0 and have to use negative numbers for the IDs. – Quentin Apr 28 '21 at 16:02