Bird
0
0

You want to run a task every 3 seconds but ensure the task never overlaps if it takes longer than 3 seconds. Which approach is best?

hard📝 Application Q15 of 15
Node.js - Timers and Scheduling
You want to run a task every 3 seconds but ensure the task never overlaps if it takes longer than 3 seconds. Which approach is best?
AUse recursive <code>setTimeout</code> scheduling the next call only after task finishes.
BUse <code>setInterval</code> with 3000ms delay and ignore task duration.
CUse <code>setTimeout</code> once without recursion.
DUse <code>setInterval</code> with 1000ms delay and check task status inside.
Step-by-Step Solution
Solution:
  1. Step 1: Understand overlap risk with setInterval

    setInterval runs tasks at fixed intervals regardless of task duration, causing overlap if task takes longer than interval.
  2. Step 2: Use recursive setTimeout to control timing

    Recursive setTimeout schedules the next run only after the current task finishes, preventing overlap.
  3. Final Answer:

    Use recursive setTimeout scheduling the next call only after task finishes. -> Option A
  4. Quick Check:

    Prevent overlap with recursive timeout [OK]
Quick Trick: Recursive timeout waits for task end before next call [OK]
Common Mistakes:
  • Using setInterval ignoring task duration
  • Not scheduling next call after task completion
  • Using too short intervals causing overlap

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes