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

Implement Debounce with Leading Edge

40 views

Problem Statement

In our production systems, we sometimes need immediate feedback for the first user interaction, but want to debounce subsequent rapid calls. Implement a leading-edge debounce that fires immediately on the first call.

Requirements

Implement a debounceLeading(func, wait) function that:

  • Invokes func immediately on the first call
  • Ignores subsequent calls within the wait period
  • After the wait period, the next call triggers immediately again
  • Preserves this context and arguments

Example Usage

const submitForm = (data) => {
  console.log(`Submitting: ${JSON.stringify(data)}`);
};

const debouncedSubmit = debounceLeading(submitForm, 1000);

debouncedSubmit({ id: 1 }); // Logs immediately: "Submitting: {"id":1}"
debouncedSubmit({ id: 2 }); // Ignored (within 1000ms)
debouncedSubmit({ id: 3 }); // Ignored (within 1000ms)

// After 1000ms...
debouncedSubmit({ id: 4 }); // Logs immediately: "Submitting: {"id":4}"

Real-world Context

Leading-edge debounce is essential for:

  • Button click handlers (prevent double-submit but respond instantly)
  • Like/upvote buttons (immediate UI feedback)
  • Navigation actions (instant response, prevent rapid navigation)

Follow-up Questions

  1. How would you extend this to support both leading and trailing edge?
  2. What edge cases should you handle for the timing?

Sample Test Cases

Case 1
Input
{"delay": 1000, "calls": [0, 100, 200]}
Expected Output
[0]
Case 2
Input
{"delay": 500, "calls": [0, 100, 700, 800]}
Expected Output
[0,700]
Case 3
Input
["func", 100, [{"args": [1], "time": 0}, {"args": [2], "time": 50}, {"args": [3], "time": 150}, {"args": [4], "time": 200}]]
Expected Output
[{"args": [1], "time": 0}, {"args": [3], "time": 150}]
Case 4
Input
["func", 50, [{"args": ["a"], "time": 0}, {"args": ["b"], "time": 10}, {"args": ["c"], "time": 20}, {"args": ["d"], "time": 60}, {"args": ["e"], "time": 70}]]
Expected Output
[{"args": ["a"], "time": 0}, {"args": ["d"], "time": 60}]
Case 5
Input
["func", 200, [{"args": [true], "time": 0}, {"args": [false], "time": 100}, {"args": [null], "time": 300}]]
Expected Output
[{"args": [true], "time": 0}, {"args": [null], "time": 300}]

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
40
Likes
0
Solutions
0
Comments
0

Category

Frontend Engineering