Bird
0
0

You want to print "Hello" every second but stop after 5 prints. Which code correctly achieves this?

hard📝 Application Q8 of 15
Node.js - Timers and Scheduling
You want to print "Hello" every second but stop after 5 prints. Which code correctly achieves this?
Alet count = 0; const id = setInterval(() => { console.log('Hello'); if (count === 5) clearInterval(id); count++; }, 1000);
Blet count = 0; const id = setInterval(() => { if (count === 5) clearInterval(id); console.log('Hello'); count++; }, 1000);
Clet count = 0; const id = setInterval(() => { console.log('Hello'); count++; if (count === 5) clearInterval(id); }, 1000);
Dlet count = 0; const id = setInterval(() => { count++; if (count > 5) clearInterval(id); console.log('Hello'); }, 1000);
Step-by-Step Solution
Solution:
  1. Step 1: Check order of operations

    Print 'Hello', then increment count, then check if count reached 5 to stop.
  2. Step 2: Validate stopping condition

    Stops exactly after 5 prints because count increments after printing.
  3. Final Answer:

    let count = 0; const id = setInterval(() => { console.log('Hello'); count++; if (count === 5) clearInterval(id); }, 1000); -> Option C
  4. Quick Check:

    Print, increment, then clearInterval at count 5 [OK]
Quick Trick: Increment count after printing, then clearInterval at limit [OK]
Common Mistakes:
  • Clearing interval before printing
  • Incrementing count after clearInterval
  • Using wrong comparison operators

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Node.js Quizzes