JS Built-ins
Closuresintermediate

Closures β€” Countdown timer

πŸ“– Usage Example
function makeCountdown(from) {
  let n = from
  return () => (n > 0 ? n-- : 0)
}
const cd = makeCountdown(3)
cd()  // β†’ 3
cd()  // β†’ 2
cd()  // β†’ 1
cd()  // β†’ 0

The countdown closure holds its own private counter, decrementing on each call and clamping at zero to prevent negative values.

Countdown from a Starting Value

Create a function that counts down from an initial value until it reaches 0, then stays at 0.

Challenge: Create a makeCountdown(from) function that returns a function. Each call decrements and returns the current value, starting at from and never going below 0.

Example:

const countdown = makeCountdown(3)
countdown() // 3
countdown() // 2
countdown() // 1
countdown() // 0
countdown() // 0
πŸ’‘ Hints (2)
  • β€’ Use a conditional to prevent negative values
  • β€’ Return the value before or after decrementing carefully