0

For the following js code:

let myAnimation;
setTimeout(function(){myAnimation = requestAnimationFrame(turn);}, 500);

Because of scope, the following code does not work to stop the animation:

btnStop.addEventListener('click', function(){cancelAnimationFrame(myAnimation);});

Any suggestion?

  • 1
    Why would you mix setTimeout and requestAnimationFrame? What are you actually trying to do? If you want "regular" animation, setTimeout does not belong here. And if you just want to schedule a timeout, there is no reason to request an animation frame. – Mike 'Pomax' Kamermans Jun 27 '21 at 00:19
  • 1
    In your case, the problem is not the scope, but the fact that the variable is empty when you click on the button (if the timeout is still running), nothing can be cancelled. Only when the timeout ends, that variable is populated. For this to work, you would need to clear the timeout as well – blex Jun 27 '21 at 00:28
  • 1
    @Mike'Pomax'Kamermans actually there would be, rAF has a more aggressive "throttle on blur" than setTimeout, so mixing both allows to have a [tree-friendly timer.](https://gist.github.com/jakearchibald/cb03f15670817001b1157e62a076fe95#gistcomment-3703736) But I doubt this is what OP is doing here :-) – Kaiido Jun 27 '21 at 00:28
  • that is true, and: that is probably true =) – Mike 'Pomax' Kamermans Jun 27 '21 at 00:29

0 Answers0