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 Flush Method

179 views

Problem Statement

Sometimes we need to immediately execute a pending debounced function—for instance, when a form is submitted or before the page unloads. Implement a debounce with both cancel and flush capabilities.

Requirements

Implement a debounce(func, wait) function that returns a debounced function with:

  • cancel() - cancels pending invocation without executing
  • flush() - immediately executes pending invocation (if any)
  • Flush should be a no-op if nothing is pending
  • After flush, the timer should be cleared

Example Usage

const autoSave = (content) => {
  console.log(`Auto-saving: ${content}`);
};

const debouncedSave = debounce(autoSave, 5000);

// User types
debouncedSave("Hello");
debouncedSave("Hello World");

// User clicks "Save Now" button
debouncedSave.flush(); // Immediately logs: "Auto-saving: Hello World"

// User continues typing
debouncedSave("Hello World!");

// Page is about to unload
window.addEventListener("beforeunload", () => {
  debouncedSave.flush(); // Ensure no data loss
});

Real-world Context

  • Auto-save with manual save option
  • Form validation with submit button
  • Analytics batching with page unload

Follow-up Questions

  1. Should flush return the result of the function call?
  2. How would you handle async functions with flush?

Sample Test Cases

Case 1
Input
{"delay": 1000, "calls": [0, 100], "flushAt": 500}
Expected Output
[500]
Case 2
Input
["func", 100]
Expected Output
{"calls": [{"args": ["arg1"]}, {"args": ["arg2"]}, {"args": ["arg3"]}], "flush_calls": [{"args": ["arg3"]}], "cancel_calls": []}
Case 3
Input
{"delay": 500, "calls": [0], "flushAt": 200}
Expected Output
[200]
Case 4
Input
["func", 100]
Expected Output
{"calls": [{"args": ["arg1"]}, {"args": ["arg2"]}], "flush_calls": [], "cancel_calls": [{"args": ["arg2"]}]}
Case 5
Input
["func", 100]
Expected Output
{"calls": [{"args": ["arg1"]}, {"args": ["arg2"]}, {"args": ["arg3"]}], "flush_calls": [{"args": ["arg2"]}], "cancel_calls": [{"args": ["arg3"]}]}

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

Category

Frontend Engineering