Coding
AI Prompt for Debounce & Throttle
Implement debounce and throttle correctly with this AI prompt: leading/trailing edge options, cleanup, and framework-specific examples that avoid leaks.
The prompt
Role: You are a frontend performance expert who implements debounce and throttle correctly — including the edge cases most tutorials skip. Context: Language: [LANGUAGE], framework: [FRAMEWORK]. Use case: [USE_CASE, e.g. search-as-you-type, window resize, scroll handler]. I need [TYPE: debounce / throttle / both — explain the difference first]. Wait/limit: [TIMING]. Edge behavior: [EDGE: leading / trailing / both]. Task: 1) Briefly explain debounce vs throttle and confirm which fits [USE_CASE]. 2) Write the implementation with correct [EDGE] behavior. 3) Include proper cleanup (cancel pending calls, remove listeners) to avoid memory leaks in [FRAMEWORK]. 4) Show integration with [USE_CASE] in a realistic example. 5) List the common mistakes (e.g. recreating the debounced function on every render). Format: Explanation first (short), then the utility code, then the integration example, then the mistakes checklist. Ask for a small timing diagram showing when calls fire for a sample input burst under your chosen edge setting. Seeing the timing visually is the fastest way to confirm leading versus trailing behavior. Constraints: The implementation must be leak-free with cleanup. Handle the [EDGE] semantics precisely — most bugs live there.
Variables to fill in
Replace each [variable] in the prompt with your own details:
[LANGUAGE] [FRAMEWORK] [USE_CASE] [TYPE] [TIMING] [EDGE]
Example input
LANGUAGE=JavaScript, USE_CASE=search-as-you-type input, WAIT=300ms, TYPE=debounce (trailing edge), FRAMEWORK=React with hooks
How to use this prompt
Name the use case — search boxes need debounce, scroll handlers need throttle, and the edge behavior (leading/trailing) depends on it. Specify the framework for idiomatic cleanup.
Tips for the best results
- The #1 bug is recreating the debounced function each render — ask the AI to show the memoization.
- Ask for a cancel/flush API if your UI needs to force execution (e.g. on form submit).
- Test the edge behavior manually: type fast, then stop, and watch when the call fires.
Frequently asked questions
Debounce or throttle — which do I need?
Debounce waits for pauses (search boxes); throttle limits rate (scroll handlers). The prompt explains and implements the one you pick.
Can one utility handle both debounce and throttle?
They solve different problems, so keep them separate. Generate both, then use debounce for pause-based triggers like search and throttle for rate-based ones like scroll.