Angular · Senior · Question 11 of 75
How do you clean up inside an effect before it re-runs or is destroyed?
effect((onCleanup) => {
const id = setInterval(() => this.poll(this.url()), 5000);
onCleanup(() => clearInterval(id));
});- ✓Correct answer: Register the cleanup with the
onCleanupcallback the effect receives - 2Return the cleanup function from
ngOnDestroyonly - 3Effects clean up all timers automatically
Explanation
The cleanup runs before the next execution (when url changes) and when the effect is destroyed with its injection context, preventing duplicated intervals.