Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2, using ngZone.runOutsideAngular with a requestAnimationFrame loop

From what i have read online the Angular team recommends that you should always call requestAnimationFrame() outside of the Angular zone like this:

this.ngZone.runOutsideAngular(() => {
  requestAnimationFrame(timestamp => {
    let timerStart = timestamp || new Date().getTime();
    this.myAnimeMethod(timestamp);
  });
});

But what about the loop ...

this.ngZone.runOutsideAngular(() => {
  requestAnimationFrame(timestamp => {
    let timerStart = timestamp;
    this.myAnimeMethod(timestamp, timerStart);
  });
});

myAnimeMethod(timestamp, timerStart) {
  let time = timestamp || new Date().getTime();
  let runtime = time - timerStart;

  /// animation logic here

  if(runtime < 10000) {

    // ------- continue to animate for 10 seconds -- //

    requestAnimationFrame(timestamp => {
      this.myAnimeMethod(timestamp, timerStart);
    });
  }
}

Was it enough to call this.ngZone.runOutsideAngular() on the first request or should i be calling it again this.ngZone.runOutsideAngular() inside myAnimeMethod() like this?

this.ngZone.runOutsideAngular(() => {
  requestAnimationFrame(timestamp => {
    let timerStart = timestamp;
    this.myAnimeMethod(timestamp, timerStart);
  });
});

myAnimeMethod(timestamp, timerStart) {
  let time = timestamp || new Date().getTime();
  let runtime = time - timerStart;

  /// animation logic here

  if(runtime < 10000) {

    // ------- request to run outside of Angular again while continuing to animate for 10 seconds -- //

    this.ngZone.runOutsideAngular(() => {
      requestAnimationFrame(timestamp => {
        this.myAnimeMethod(timestamp, timerStart);
      });
    });

  }
}
like image 773
DevMike Avatar asked Apr 26 '26 23:04

DevMike


1 Answers

Short answer: You don't need to continue to call NgZone.runOutsideAngular from a requestAnimationFrame handler that came from a call outside Angular.

Long answer: Once you're in the "root" zone (which is what you get when you call NgZone.runOutsideAngular), any requestAnimationFrame callbacks will also run from that zone unless you explicitly request a different zone, e.g. via NgZone.run.

To check this, try calling the static function NgZone.isInAngularZone() from your requestAnimationFrame handler.

Note that I tested this with Angular 4.4.4 and Zone.js 0.8.18.

like image 91
fr0 Avatar answered Apr 29 '26 23:04

fr0