How to Error handle the requestAnimationFrame function

Viewed 245

Looking for a way to check for any errors in the animate() function. If there are any errors that happen in the animate() function my browser crashes and my computer heats up.

I tried to have the code in a try/catch handler but this doesn't work

animate(){
    this.renderer.render(this.scene, this.camera);

    try {
       // functions that update scene
    } catch (error) {
        gsap.ticker.remove(() => this.animate());
        console.error(error);
    }
}

Codepen Example

Any suggestions how to correctly error handle with a 'requestAnimationFrame'/gsap.tick loop?

1 Answers

The reason why your .remove() function doesn't remove the function is because when you use an arrow function you're creating a new function each time. So it tries to remove a new function that it just created instead of the function inside of the .add().

I think you're wanting to do something like this? Demo

animate() {
  const myThis = window.tunnel;
  try {
    // Working version
    myThis.renderer.render(myThis.scene, myThis.camera); 

    // Error version (to show it works)
    // this.renderer.render(this.scene, this.camera);
  } catch (error) {
    gsap.ticker.remove(myThis.animate);
    console.error(error);
  }
}
Related