Debounce Function

Debounce Function

Medium NodeJS Async & Event Loop 30 views
Explanation Complexity

Problem Statement

Build a debounce(fn, ms) and show it only calls once.

Input Format

No input.

Output Format

Print integer calls.

Constraints

Call debounced function many times quickly.

Input / Output Format

Input Format
No input.
Output Format
Print integer calls.
Constraints
Call debounced function many times quickly.

Examples

Input:
Output:
1

Example Solution (Public)

NodeJS
function debounce(fn, ms) {
  let id;
  return (...args) => {
    clearTimeout(id);
    id = setTimeout(() => fn(...args), ms);
  };
}

let calls = 0;
const d = debounce(() => { calls += 1; console.log(calls); }, 30);
d();
d();
d();

Official Solution Code

function debounce(fn, ms) {
  let id;
  return (...args) => {
    clearTimeout(id);
    id = setTimeout(() => fn(...args), ms);
  };
}

let calls = 0;
const d = debounce(() => { calls += 1; console.log(calls); }, 30);
d();
d();
d();
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.