Angular 2 using ngZone.runOutside Angular with requestAnimationFrame outline
From what I've read online, the Angular team recommends that you always call requestAnimationFrame()
outside of Angular's 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 do I need to call it again this.ngZone.runOutsideAngular()
internally myAnimeMethod()
?
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);
});
});
}
}
source to share
Short answer: you don't need to keep calling NgZone.runOutsideAngular
from a handler requestAnimationFrame
that comes from an external call to Angular.
Long answer: once you hit the "root" zone (which is what you get when called NgZone.runOutsideAngular
), any callbacks requestAnimationFrame
will also be executed from that zone, unless you explicitly request another zone, for example. through NgZone.run
.
To test this, try calling a static function NgZone.isInAngularZone()
from your handler requestAnimationFrame
.
Note that I've tested this with Angular 4.4.4 and Zone.js 0.8.18.
source to share