{"id":"6b093dddbd4755deb67ee061","slug":"debounce-throttle","title":"Debounce and throttle","summary":"Two classic frontend higher-order functions – debounce (call after silence) and throttle (at most once per period) – with cancel, flush, preserved this and injected timers.","servedLang":"en","availableLangs":["pl","en"],"kind":"code","category":"algorithms","status":"published","difficulty":"medium","topics":["decorator"],"techs":["typescript","javascript"],"tags":["javascript","closures","timers","event-loop","higher-order-functions"],"languages":[{"lang":"typescript","runner":"browser","starter":"interface Timer {\n  setTimeout(fn: () => void, ms: number): unknown;\n  clearTimeout(id: unknown): void;\n}\n\nconst defaultTimer: Timer = {\n  setTimeout: (fn, ms) => setTimeout(fn, ms),\n  clearTimeout: (id) => clearTimeout(id as number),\n};\n\ntype Debounced<A extends unknown[]> = ((...args: A) => void) & { cancel(): void; flush(): void };\ntype Throttled<A extends unknown[]> = ((...args: A) => void) & { cancel(): void };\n\n/** Calls fn after waitMs of silence with the last arguments and `this`. */\nfunction debounce<A extends unknown[]>(fn: (...args: A) => void, waitMs: number, timer: Timer = defaultTimer): Debounced<A> {\n  // TODO\n  throw new Error('Not implemented');\n}\n\n/** Calls fn at most once per intervalMs: leading call now, trailing call with the last arguments. */\nfunction throttle<A extends unknown[]>(fn: (...args: A) => void, intervalMs: number, timer: Timer = defaultTimer): Throttled<A> {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":10,"tests":"class FakeTimers {\n  now = 0;\n  queue = [];\n  seq = 0;\n  setTimeout = (fn, ms) => {\n    const id = ++this.seq;\n    this.queue.push({ id, at: this.now + ms, fn });\n    return id;\n  };\n  clearTimeout = (id) => {\n    this.queue = this.queue.filter((t) => t.id !== id);\n  };\n  advance(ms) {\n    const end = this.now + ms;\n    for (;;) {\n      this.queue.sort((a, b) => a.at - b.at || a.id - b.id);\n      const next = this.queue[0];\n      if (!next || next.at > end) break;\n      this.queue.shift();\n      this.now = next.at;\n      next.fn();\n    }\n    this.now = end;\n  }\n}\n\nfunction spy() {\n  const calls = [];\n  const fn = function (...args) {\n    calls.push({ args, self: this, at: fn.timers ? fn.timers.now : null });\n  };\n  fn.calls = calls;\n  return fn;\n}\n\ntest('debounce: one call after the silence, with the last arguments', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const d = debounce(fn, 100, timers);\n  d(1);\n  timers.advance(50);\n  d(2);\n  timers.advance(50);\n  d(3);\n  timers.advance(99);\n  expect(fn.calls).toHaveLength(0);\n  timers.advance(1);\n  expect(fn.calls.map((c) => c.args)).toEqual([[3]]);\n});\n\ntest('debounce: separate bursts give separate calls, arguments are forwarded', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const d = debounce(fn, 100, timers);\n  d('a', 1, true);\n  timers.advance(100);\n  d('b');\n  timers.advance(100);\n  expect(fn.calls.map((c) => c.args)).toEqual([['a', 1, true], ['b']]);\n});\n\ntest('debounce: keeps `this` of the last call', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const obj = { name: 'search', onInput: debounce(fn, 10, timers) };\n  obj.onInput('x');\n  timers.advance(10);\n  expect(fn.calls[0].self).toBe(obj);\n});\n\ntest('debounce: cancel and flush', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const d = debounce(fn, 100, timers);\n  d(1);\n  d.cancel();\n  timers.advance(1000);\n  expect(fn.calls).toHaveLength(0);\n  expect(timers.queue).toHaveLength(0);\n  d(7);\n  d.flush();\n  expect(fn.calls.map((c) => c.args)).toEqual([[7]]);\n  timers.advance(1000);\n  d.flush();\n  expect(fn.calls).toHaveLength(1);\n});\n\ntest('throttle: leading call now, trailing call at the end of the period', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  fn.timers = timers;\n  const t = throttle(fn, 100, timers);\n  t(1);\n  timers.advance(30);\n  t(2);\n  timers.advance(30);\n  t(3);\n  expect(fn.calls.map((c) => c.args)).toEqual([[1]]);\n  timers.advance(40);\n  expect(fn.calls.map((c) => [c.args[0], c.at])).toEqual([[1, 0], [3, 100]]);\n});\n\ntest('throttle: the trailing call starts a new period', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  fn.timers = timers;\n  const t = throttle(fn, 100, timers);\n  t(1);\n  timers.advance(50);\n  t(2);\n  timers.advance(70); // trailing fn(2) at 100, next period until 200\n  t(3);\n  expect(fn.calls).toHaveLength(2);\n  timers.advance(80);\n  expect(fn.calls.map((c) => [c.args[0], c.at])).toEqual([[1, 0], [2, 100], [3, 200]]);\n});\n\ntest('throttle: goes idle after a quiet period, keeps `this`', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const obj = { onScroll: throttle(fn, 100, timers) };\n  obj.onScroll(1);\n  timers.advance(150);\n  obj.onScroll(2);\n  expect(fn.calls.map((c) => c.args)).toEqual([[1], [2]]);\n  expect(fn.calls[1].self).toBe(obj);\n});\n\ntest('throttle: cancel drops the trailing call', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const t = throttle(fn, 100, timers);\n  t(1);\n  t(2);\n  t.cancel();\n  timers.advance(1000);\n  expect(fn.calls.map((c) => c.args)).toEqual([[1]]);\n  t(3);\n  expect(fn.calls.map((c) => c.args)).toEqual([[1], [3]]);\n});\n\ntest('default timers are the real ones', async () => {\n  const fn = spy();\n  const d = debounce(fn, 20);\n  d('real');\n  d('timers');\n  await new Promise((resolve) => setTimeout(resolve, 80));\n  expect(fn.calls.map((c) => c.args)).toEqual([['timers']]);\n});\n\ntest('performance: 100 000 calls, at most one active timer', () => {\n  const timers = new FakeTimers();\n  const df = spy();\n  const tf = spy();\n  const d = debounce(df, 5, timers);\n  const t = throttle(tf, 10, timers);\n  let maxTimers = 0;\n  for (let i = 0; i < 100000; i++) {\n    d(i);\n    t(i);\n    maxTimers = Math.max(maxTimers, timers.queue.length);\n    timers.advance(1);\n  }\n  timers.advance(100);\n  expect(maxTimers).toBeLessThanOrEqual(2);\n  expect(df.calls.map((c) => c.args)).toEqual([[99999]]);\n  expect(tf.calls).toHaveLength(10001);\n  expect(tf.calls[tf.calls.length - 1].args).toEqual([99999]);\n});\n"},{"lang":"javascript","runner":"browser","starter":"const defaultTimer = {\n  setTimeout: (fn, ms) => setTimeout(fn, ms),\n  clearTimeout: (id) => clearTimeout(id),\n};\n\n/**\n * Calls fn after waitMs of silence with the last arguments and `this`.\n * The result has cancel() and flush().\n */\nfunction debounce(fn, waitMs, timer = defaultTimer) {\n  // TODO\n  throw new Error('Not implemented');\n}\n\n/**\n * Calls fn at most once per intervalMs: immediately (leading) and once more\n * at the end of the period with the last arguments (trailing). The result has cancel().\n */\nfunction throttle(fn, intervalMs, timer = defaultTimer) {\n  // TODO\n  throw new Error('Not implemented');\n}\n","testCount":10,"tests":"class FakeTimers {\n  now = 0;\n  queue = [];\n  seq = 0;\n  setTimeout = (fn, ms) => {\n    const id = ++this.seq;\n    this.queue.push({ id, at: this.now + ms, fn });\n    return id;\n  };\n  clearTimeout = (id) => {\n    this.queue = this.queue.filter((t) => t.id !== id);\n  };\n  advance(ms) {\n    const end = this.now + ms;\n    for (;;) {\n      this.queue.sort((a, b) => a.at - b.at || a.id - b.id);\n      const next = this.queue[0];\n      if (!next || next.at > end) break;\n      this.queue.shift();\n      this.now = next.at;\n      next.fn();\n    }\n    this.now = end;\n  }\n}\n\nfunction spy() {\n  const calls = [];\n  const fn = function (...args) {\n    calls.push({ args, self: this, at: fn.timers ? fn.timers.now : null });\n  };\n  fn.calls = calls;\n  return fn;\n}\n\ntest('debounce: one call after the silence, with the last arguments', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const d = debounce(fn, 100, timers);\n  d(1);\n  timers.advance(50);\n  d(2);\n  timers.advance(50);\n  d(3);\n  timers.advance(99);\n  expect(fn.calls).toHaveLength(0);\n  timers.advance(1);\n  expect(fn.calls.map((c) => c.args)).toEqual([[3]]);\n});\n\ntest('debounce: separate bursts give separate calls, arguments are forwarded', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const d = debounce(fn, 100, timers);\n  d('a', 1, true);\n  timers.advance(100);\n  d('b');\n  timers.advance(100);\n  expect(fn.calls.map((c) => c.args)).toEqual([['a', 1, true], ['b']]);\n});\n\ntest('debounce: keeps `this` of the last call', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const obj = { name: 'search', onInput: debounce(fn, 10, timers) };\n  obj.onInput('x');\n  timers.advance(10);\n  expect(fn.calls[0].self).toBe(obj);\n});\n\ntest('debounce: cancel and flush', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const d = debounce(fn, 100, timers);\n  d(1);\n  d.cancel();\n  timers.advance(1000);\n  expect(fn.calls).toHaveLength(0);\n  expect(timers.queue).toHaveLength(0);\n  d(7);\n  d.flush();\n  expect(fn.calls.map((c) => c.args)).toEqual([[7]]);\n  timers.advance(1000);\n  d.flush();\n  expect(fn.calls).toHaveLength(1);\n});\n\ntest('throttle: leading call now, trailing call at the end of the period', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  fn.timers = timers;\n  const t = throttle(fn, 100, timers);\n  t(1);\n  timers.advance(30);\n  t(2);\n  timers.advance(30);\n  t(3);\n  expect(fn.calls.map((c) => c.args)).toEqual([[1]]);\n  timers.advance(40);\n  expect(fn.calls.map((c) => [c.args[0], c.at])).toEqual([[1, 0], [3, 100]]);\n});\n\ntest('throttle: the trailing call starts a new period', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  fn.timers = timers;\n  const t = throttle(fn, 100, timers);\n  t(1);\n  timers.advance(50);\n  t(2);\n  timers.advance(70); // trailing fn(2) at 100, next period until 200\n  t(3);\n  expect(fn.calls).toHaveLength(2);\n  timers.advance(80);\n  expect(fn.calls.map((c) => [c.args[0], c.at])).toEqual([[1, 0], [2, 100], [3, 200]]);\n});\n\ntest('throttle: goes idle after a quiet period, keeps `this`', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const obj = { onScroll: throttle(fn, 100, timers) };\n  obj.onScroll(1);\n  timers.advance(150);\n  obj.onScroll(2);\n  expect(fn.calls.map((c) => c.args)).toEqual([[1], [2]]);\n  expect(fn.calls[1].self).toBe(obj);\n});\n\ntest('throttle: cancel drops the trailing call', () => {\n  const timers = new FakeTimers();\n  const fn = spy();\n  const t = throttle(fn, 100, timers);\n  t(1);\n  t(2);\n  t.cancel();\n  timers.advance(1000);\n  expect(fn.calls.map((c) => c.args)).toEqual([[1]]);\n  t(3);\n  expect(fn.calls.map((c) => c.args)).toEqual([[1], [3]]);\n});\n\ntest('default timers are the real ones', async () => {\n  const fn = spy();\n  const d = debounce(fn, 20);\n  d('real');\n  d('timers');\n  await new Promise((resolve) => setTimeout(resolve, 80));\n  expect(fn.calls.map((c) => c.args)).toEqual([['timers']]);\n});\n\ntest('performance: 100 000 calls, at most one active timer', () => {\n  const timers = new FakeTimers();\n  const df = spy();\n  const tf = spy();\n  const d = debounce(df, 5, timers);\n  const t = throttle(tf, 10, timers);\n  let maxTimers = 0;\n  for (let i = 0; i < 100000; i++) {\n    d(i);\n    t(i);\n    maxTimers = Math.max(maxTimers, timers.queue.length);\n    timers.advance(1);\n  }\n  timers.advance(100);\n  expect(maxTimers).toBeLessThanOrEqual(2);\n  expect(df.calls.map((c) => c.args)).toEqual([[99999]]);\n  expect(tf.calls).toHaveLength(10001);\n  expect(tf.calls[tf.calls.length - 1].args).toEqual([99999]);\n});\n"}],"questionCount":null,"xp":20,"stats":{"attempts":0,"solves":0,"solutions":0,"comments":0},"solveRate":null,"publishedAt":"2026-11-27T08:22:53.681Z","requestedLang":"en","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"A search box should not send a request on every keystroke, and a scroll handler should not recompute the layout 120 times per second. Two wrapper functions help, and frontend interviews ask about them all the time. The task is about JavaScript/TypeScript – timers, closures and "},{"type":"text","text":"this","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"heading","attrs":{"level":2,"id":"task"},"content":[{"type":"text","text":"Task"}]},{"type":"paragraph","content":[{"type":"text","text":"Both functions take an optional "},{"type":"text","text":"timer = { setTimeout(fn, ms), clearTimeout(id) }","marks":[{"type":"code"}]},{"type":"text","text":" object (the global "},{"type":"text","text":"setTimeout","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"clearTimeout","marks":[{"type":"code"}]},{"type":"text","text":" by default) – the tests plug in fake timers and control time."}]},{"type":"paragraph","content":[{"type":"text","text":"debounce(fn, waitMs, timer?)","marks":[{"type":"code"}]},{"type":"text","text":" returns a function that:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"calls "},{"type":"text","text":"fn","marks":[{"type":"code"}]},{"type":"text","text":" only after "},{"type":"text","text":"waitMs","marks":[{"type":"code"}]},{"type":"text","text":" ms of "},{"type":"text","text":"silence","marks":[{"type":"bold"}]},{"type":"text","text":" – every new call during that time postpones it,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"passes "},{"type":"text","text":"fn","marks":[{"type":"code"}]},{"type":"text","text":" the arguments and "},{"type":"text","text":"this","marks":[{"type":"code"}]},{"type":"text","text":" of the "},{"type":"text","text":"last","marks":[{"type":"bold"}]},{"type":"text","text":" call,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"has a "},{"type":"text","text":"cancel()","marks":[{"type":"code"}]},{"type":"text","text":" method – drops the pending call,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"has a "},{"type":"text","text":"flush()","marks":[{"type":"code"}]},{"type":"text","text":" method – if a call is pending, runs "},{"type":"text","text":"fn","marks":[{"type":"code"}]},{"type":"text","text":" immediately (and cancels the timer); otherwise does nothing."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"throttle(fn, intervalMs, timer?)","marks":[{"type":"code"}]},{"type":"text","text":" returns a function that:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"on the first call (when nothing is in progress) calls "},{"type":"text","text":"fn","marks":[{"type":"code"}]},{"type":"text","text":" "},{"type":"text","text":"immediately","marks":[{"type":"bold"}]},{"type":"text","text":" and starts an "},{"type":"text","text":"intervalMs","marks":[{"type":"code"}]},{"type":"text","text":" period,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"remembers calls made during the period (the last arguments and "},{"type":"text","text":"this","marks":[{"type":"code"}]},{"type":"text","text":"); at the end of the period, if there was at least one such call, calls "},{"type":"text","text":"fn","marks":[{"type":"code"}]},{"type":"text","text":" once with the last arguments and starts "},{"type":"text","text":"another","marks":[{"type":"bold"}]},{"type":"text","text":" period,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"when a period passes without calls, goes back to idle – the next call is immediate again,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"has a "},{"type":"text","text":"cancel()","marks":[{"type":"code"}]},{"type":"text","text":" method – drops the remembered call and goes back to idle."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"example"},"content":[{"type":"text","text":"Example"}]},{"type":"paragraph","content":[{"type":"text","text":"waitMs = intervalMs = 100","marks":[{"type":"code"}]},{"type":"text","text":", calls with arguments "},{"type":"text","text":"1","marks":[{"type":"code"}]},{"type":"text","text":" (0 ms), "},{"type":"text","text":"2","marks":[{"type":"code"}]},{"type":"text","text":" (30 ms), "},{"type":"text","text":"3","marks":[{"type":"code"}]},{"type":"text","text":" (60 ms):"}]},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Function"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Calls of "},{"type":"text","text":"fn","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"debounce","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"fn(3)","marks":[{"type":"code"}]},{"type":"text","text":" at 160 ms"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"throttle","marks":[{"type":"code"}]}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"fn(1)","marks":[{"type":"code"}]},{"type":"text","text":" at 0 ms, "},{"type":"text","text":"fn(3)","marks":[{"type":"code"}]},{"type":"text","text":" at 100 ms"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"constraints"},"content":[{"type":"text","text":"Constraints"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Up to 100,000 calls in the performance test; at any moment at most one timer should be active."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"expected-complexity"},"content":[{"type":"text","text":"Expected complexity"}]},{"type":"paragraph","content":[{"type":"text","text":"Every call of the wrapped function "},{"type":"text","text":"O(1)","marks":[{"type":"bold"}]},{"type":"text","text":"."}]}]},"hints":[],"hintsCount":3,"quiz":null,"solutionNotes":null,"unlocked":false,"external":[{"provider":"leetcode","url":"https://leetcode.com/problems/debounce/","title":"LeetCode 2627 – Debounce","difficulty":null}],"articles":[{"id":"6b08bd3d80884893657cc9fb","slug":"proxy","title":"Proxy – a stand-in that controls access to the real object"},{"id":"6b08bd3280884893657cc938","slug":"decorator","title":"Decorator – adding behaviour layer by layer"},{"id":"6b08bd3180884893657cc91a","slug":"composite","title":"Composite – trees in which a leaf and a branch look the same"},{"id":"6b08bd2f80884893657cc8de","slug":"adapter","title":"Adapter – how to get along with code that speaks another language"}],"topicsInfo":[{"slug":"decorator","title":"Decorator","group":"structural","icon":"layers"}],"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"capabilities":{"judge0":false,"aiReview":false},"createdAt":"2026-11-27T08:22:53.683Z","updatedAt":"2026-11-27T08:22:53.683Z"}