Skip to content
WANCODE
BM

Stop the Infinite Loop

12 minBeginnerDebugging

Click Calculate and the page freezes for a moment, then the console shows "Stopped a loop that ran for more than 1.5s". That message comes from WANCode's loop guard — in a normal browser tab this bug would freeze the page until the browser offered to kill it.

JavaScript
yearsToTarget(1000, 2000, 0.05)  // 15   (RM1000 at 5% a year)
yearsToTarget(100, 800, 1)       // 3    (doubles: 200, 400, 800)
yearsToTarget(5000, 2000, 0.05)  // 0    (already there)
yearsToTarget(1000, 2000, 0)     // -1   (0% interest never grows)

Expected results

Requirements

  • Each year the balance becomes balance * (1 + rate). Count the whole years until it is at least target.
  • If balance is already ≥ target, return 0.
  • If the goal can never be reached (rate <= 0 or balance <= 0), return -1 instead of looping forever.

Fix yearsToTarget(balance, target, rate) so its loop always ends: return the number of years to reach the goal, 0 if it's already reached, and -1 if the balance can never grow (rate or balance ≤ 0).

Checks

  • The loop finishes with the right answer
  • Returns 0 when the goal is already reached
  • Returns -1 instead of looping forever
Preview

Console output from your code appears here.

Step 1 of 1