Bird
0
0

Consider this Angular component code snippet:

medium📝 component behavior Q13 of 15
Angular - Lifecycle Hooks
Consider this Angular component code snippet:
export class TimerComponent implements OnDestroy {
  intervalId = setInterval(() => console.log('tick'), 1000);

  ngOnDestroy() {
    clearInterval(this.intervalId);
    console.log('Timer stopped');
  }
}

What will happen when this component is removed from the view?
AThe interval stops and logs 'Timer stopped' once
BAn error occurs because clearInterval is not valid here
CNothing happens because ngOnDestroy is not called automatically
DThe interval keeps running and logs 'tick' every second
Step-by-Step Solution
Solution:
  1. Step 1: Understand what ngOnDestroy does here

    When the component is removed, Angular calls ngOnDestroy, which clears the interval timer.
  2. Step 2: Effect of clearing the interval

    Clearing the interval stops the repeated 'tick' logs, and the message 'Timer stopped' is logged once.
  3. Final Answer:

    The interval stops and logs 'Timer stopped' once -> Option A
  4. Quick Check:

    ngOnDestroy clears timer = The interval stops and logs 'Timer stopped' once [OK]
Quick Trick: ngOnDestroy stops timers to prevent leaks [OK]
Common Mistakes:
  • Thinking interval keeps running after destroy
  • Assuming ngOnDestroy is not called
  • Confusing clearInterval usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes