cancel animation in typescript

To cancel an animation in TypeScript, you can use the cancelAnimationFrame function along with requestAnimationFrame. The requestAnimationFrame function is used to schedule a function to run on the next animation frame, while the cancelAnimationFrame function is used to cancel a previously scheduled animation frame.

Here's an example code that illustrates how to use these two functions to cancel an animation:

index.ts
let animationId: number;

function animate() {
  // Do animation logic here
  animationId = requestAnimationFrame(animate);
}

// Start animation
animationId = requestAnimationFrame(animate);

// Cancel animation
function cancelAnimation() {
  cancelAnimationFrame(animationId);
}
281 chars
15 lines

In the above code, we first define a variable animationId that stores the ID of the animation frame that's currently scheduled. We then define an animate function that contains the animation logic and schedules itself to run on the next animation frame.

To start the animation, we call requestAnimationFrame and pass in the animate function. This schedules the animate function to run on the next animation frame and returns an ID that we store in the animationId variable.

To cancel the animation, we call cancelAnimationFrame and pass in the animationId variable. This cancels the previously scheduled animation frame and stops the animation.

gistlibby LogSnag