DevPrep
  • Interview Prep
  • Projects
  • Resources
  • Pricing
  • About Us
Submit Question
DevPrep
  • Pricing
  • About Us
Submit Question

Practice

  • JavaScript
  • DSA
  • Machine Coding
  • System Design

Resources

  • Learning Tracks
  • Articles
  • Roadmaps
  • Compare Concepts
  • Glossary
  • Developer Tools
  • All Questions

Company

  • About
  • Pricing

Legal

  • Privacy Policy
  • Terms of Service
DevPrep

© 2026 DevPrep. All rights reserved.

← Back to Questions
MediumJavaScript

useTimeout()

11 views

We are building a Live Auction App. When a user places a bid, we need to show a 'Success' message that automatically disappears after 5 seconds. However, we've noticed two major bugs in our prototype:

  1. If the user navigates away from the page before the 5 seconds are up, the app crashes because it tries to update the state of an unmounted component.

  2. If the user places a second bid while the first timer is still running, the timers overlap, causing the message to flicker and disappear too early.

The Task: Implement a production-ready useTimeout(callback, delay) hook that:

  • Encapsulates Lifecycle: Automatically handles setTimeout and clearTimeout.

  • Prevents Memory Leaks: Ensures no code runs after the component unmounts.

  • Supports Dynamic Pausing: If the delay passed is null, the timer should stop (useful for 'pausing' an action if the user hovers over the message).

  • Solves Stale Closures: If the callback changes (e.g., it relies on new state), the timeout must always execute the latest version of that logic without you having to manually reset the timer every single time a dependency changes.

Sample Test Cases

Case 1
Input
["callback1", 100]
Expected Output
{"setup": true, "clear": false, "execute": "callback1"}
Case 2
Input
["callback2", null]
Expected Output
{"setup": false, "clear": false, "execute": null}
Case 3
Input
["callback3", 0]
Expected Output
{"setup": true, "clear": false, "execute": "callback3"}

No solutions yet

Be the first to share a solution for this question.

Comments (0)

Sign in to leave a comment.

No comments yet. Be the first to comment.

Stats

Views
11
Likes
0
Solutions
0
Comments
0

Category

Frontend Engineering