Description

When dealing with unreliable APIs or failing services, continuously retrying failed operations can make the system unstable.

To prevent this, developers use a Circuit Breaker — a pattern that halts repeated calls after a certain number of failures and resumes automatically after a cooldown period.

In this challenge, you’ll build your own version of a Circuit Breaker that temporarily stops a function from being executed after multiple consecutive errors.


Your Task

Implement a function circuitBreaker(fn, retryLimit, time) that returns a wrapped function which:

  • Executes fn() normally until it fails consecutively more than retryLimit times.
  • After exceeding the retry limit, logs "service not available" and stops calling fn for time milliseconds.
  • Automatically resets after the cooldown period and resumes normal execution.

Method

Function

Description

circuitBreaker(fn, retryLimit, time)

Returns a protected version of fn that halts after repeated failures and resumes after cooldown.


Example

Input

const testFunction = () => {
let count = 0;
return function () {
count++;
if (count < 4) {
throw "failed";
} else {
return "hello";
}
};
};

let t = testFunction();
let c = circuitBreaker(t, 3, 200);

c(); // "error"
c(); // "error"
c(); // "error"

// circuit is now open (service temporarily halted)
c(); // "service not available"
c(); // "service not available"

// after 200ms, it should resume
setTimeout(() => {
console.log(c()); // "hello"
}, 250);

Expected Output

error
error
error
service not available
service not available
hello

Expected Behavior

✅ Stops function calls after the retry threshold is reached
✅ Prints "service not available" when the circuit is open
✅ Automatically resets after the cooldown time
✅ Resumes execution normally afterward


Hints

Hint 1

Use a closure to track retryCount and circuit state (isHalted).

Hint 2

Use setTimeout to reset the breaker after cooldown.

Hint 3

Wrap function calls in a try–catch block to catch and count errors.