Implement a JavaScript function createStaleClosureDemo that simulates a common "Stale Closure" problem often found in React hooks like useEffect or useCallback, and provide a solution to fix it.
The Scenario
You have a counter that increments every second using setInterval. However, the function passed to setInterval "captures" the initial value of the counter and refuses to update, even though the counter itself is changing.
Requirements
- Create a function
createCounter()that returns an object with:increment(): A method to increase the count.logDelayed(): A method that usessetTimeoutto log the count after 1 second.
- Demonstrate the "Stale" bug where
logDelayedlogs an old value ifincrementis called quickly after. - Implement a "Fixed" version using a Functional Update or Ref-based approach.
Example Behavior
Constraints
- Use only vanilla JavaScript (ES6+).
- The solution must explain why the closure became stale.