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

75 views

Problem Statement

In complex applications, we need the ability to cancel pending debounced operations—for example, when a component unmounts or when the user navigates away. Implement a debounce function with a cancel capability.

Requirements

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

  • A cancel() method that cancels any pending invocation
  • Standard debounce behavior (trailing edge)
  • The cancel method should be safe to call multiple times

Example Usage

const saveToServer = (data) => {
  console.log(`Saving: ${JSON.stringify(data)}`);
  return fetch("/api/save", { method: "POST", body: JSON.stringify(data) });
};

const debouncedSave = debounce(saveToServer, 2000);

// User makes changes
debouncedSave({ content: "draft 1" });
debouncedSave({ content: "draft 2" });

// User navigates away before 2 seconds
debouncedSave.cancel();
// Nothing is saved - pending call was cancelled

// React useEffect cleanup example
useEffect(() => {
  const debouncedHandler = debounce(handleResize, 150);
  window.addEventListener("resize", debouncedHandler);
  
  return () => {
    debouncedHandler.cancel(); // Cleanup!
    window.removeEventListener("resize", debouncedHandler);
  };
}, []);

Follow-up Questions

  1. How would you implement a pending() method to check if there's a pending call?
  2. Should cancel return anything? What would be useful?

Sample Test Cases

Case 1
Input
{"delay": 1000, "calls": [0, 100], "cancelAt": 500}
Expected Output
[]
Case 2
Input
{"delay": 500, "calls": [0, 100, 700], "cancelAt": 400}
Expected Output
[1200]
Case 3
Input
["func", 100, [{"args": [1], "delay": 0}, {"args": [2], "delay": 50}, {"args": [3], "delay": 120, "cancel": true}, {"args": [4], "delay": 150}]]
Expected Output
{"funcCalls": []}
Case 4
Input
["func", 50, [{"args": [1], "delay": 0}, {"args": [2], "delay": 20}, {"args": [3], "delay": 60}]]
Expected Output
{"funcCalls": [{"args": [3], "delay": 110}]}
Case 5
Input
["func", 200, [{"args": [1], "delay": 0, "cancel": true}, {"args": [2], "delay": 50, "cancel": true}, {"args": [3], "delay": 100, "cancel": true}]]
Expected Output
{"funcCalls": []}

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

Category

Frontend Engineering