{"id":"6b093dddbd4755deb67ee061","slug":"debounce-throttle","title":"Debounce i throttle","summary":"Dwie klasyczne funkcje wyższego rzędu z frontendu – debounce (wywołaj po ciszy) i throttle (najwyżej raz na okres) – z cancel, flush, zachowaniem this i wstrzykiwanymi timerami.","servedLang":"pl","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":"pl","statement":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Pole wyszukiwania nie powinno wysyłać żądania po każdym naciśnięciu klawisza, a obsługa przewijania nie powinna liczyć układu strony 120 razy na sekundę. Pomagają dwie funkcje opakowujące, o które na rozmowach frontendowych pyta się bardzo często. Zadanie dotyczy JavaScriptu/TypeScriptu – timerów, domknięć i "},{"type":"text","text":"this","marks":[{"type":"code"}]},{"type":"text","text":"."}]},{"type":"heading","attrs":{"level":2,"id":"zadanie"},"content":[{"type":"text","text":"Zadanie"}]},{"type":"paragraph","content":[{"type":"text","text":"Obie funkcje przyjmują opcjonalny obiekt "},{"type":"text","text":"timer = { setTimeout(fn, ms), clearTimeout(id) }","marks":[{"type":"code"}]},{"type":"text","text":" (domyślnie globalne "},{"type":"text","text":"setTimeout","marks":[{"type":"code"}]},{"type":"text","text":"/"},{"type":"text","text":"clearTimeout","marks":[{"type":"code"}]},{"type":"text","text":") – testy podstawiają sztuczne timery i sterują czasem."}]},{"type":"paragraph","content":[{"type":"text","text":"debounce(fn, waitMs, timer?)","marks":[{"type":"code"}]},{"type":"text","text":" zwraca funkcję, która:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"wywołuje "},{"type":"text","text":"fn","marks":[{"type":"code"}]},{"type":"text","text":" dopiero po "},{"type":"text","text":"waitMs","marks":[{"type":"code"}]},{"type":"text","text":" ms "},{"type":"text","text":"ciszy","marks":[{"type":"bold"}]},{"type":"text","text":" – każde kolejne wywołanie w tym czasie odkłada termin,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"przekazuje "},{"type":"text","text":"fn","marks":[{"type":"code"}]},{"type":"text","text":" argumenty i "},{"type":"text","text":"this","marks":[{"type":"code"}]},{"type":"text","text":" z "},{"type":"text","text":"ostatniego","marks":[{"type":"bold"}]},{"type":"text","text":" wywołania,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ma metodę "},{"type":"text","text":"cancel()","marks":[{"type":"code"}]},{"type":"text","text":" – porzuca oczekujące wywołanie,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ma metodę "},{"type":"text","text":"flush()","marks":[{"type":"code"}]},{"type":"text","text":" – jeśli coś czeka, wywołuje "},{"type":"text","text":"fn","marks":[{"type":"code"}]},{"type":"text","text":" natychmiast (i anuluje timer); jeśli nie – nic nie robi."}]}]}]},{"type":"paragraph","content":[{"type":"text","text":"throttle(fn, intervalMs, timer?)","marks":[{"type":"code"}]},{"type":"text","text":" zwraca funkcję, która:"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"przy pierwszym wywołaniu (gdy nic nie trwa) wywołuje "},{"type":"text","text":"fn","marks":[{"type":"code"}]},{"type":"text","text":" "},{"type":"text","text":"od razu","marks":[{"type":"bold"}]},{"type":"text","text":" i zaczyna okres "},{"type":"text","text":"intervalMs","marks":[{"type":"code"}]},{"type":"text","text":","}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"wywołania w trakcie okresu zapamiętuje (ostatnie argumenty i "},{"type":"text","text":"this","marks":[{"type":"code"}]},{"type":"text","text":"); na końcu okresu, jeśli było choć jedno takie wywołanie, wywołuje "},{"type":"text","text":"fn","marks":[{"type":"code"}]},{"type":"text","text":" raz z ostatnimi argumentami i zaczyna "},{"type":"text","text":"kolejny","marks":[{"type":"bold"}]},{"type":"text","text":" okres,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"gdy okres minie bez wywołań, wraca do stanu spoczynku – następne wywołanie znów jest natychmiastowe,"}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"ma metodę "},{"type":"text","text":"cancel()","marks":[{"type":"code"}]},{"type":"text","text":" – porzuca zapamiętane wywołanie i wraca do stanu spoczynku."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"przyklad"},"content":[{"type":"text","text":"Przykład"}]},{"type":"paragraph","content":[{"type":"text","text":"waitMs = intervalMs = 100","marks":[{"type":"code"}]},{"type":"text","text":", wywołania z argumentami "},{"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":"Funkcja"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Wywołania "},{"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":" w 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":" w 0 ms, "},{"type":"text","text":"fn(3)","marks":[{"type":"code"}]},{"type":"text","text":" w 100 ms"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"ograniczenia"},"content":[{"type":"text","text":"Ograniczenia"}]},{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Do 100 000 wywołań w teście wydajnościowym; w każdej chwili powinien istnieć najwyżej jeden aktywny timer."}]}]}]},{"type":"heading","attrs":{"level":2,"id":"oczekiwana-zlozonosc"},"content":[{"type":"text","text":"Oczekiwana złożoność"}]},{"type":"paragraph","content":[{"type":"text","text":"Każde wywołanie opakowanej funkcji "},{"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":"Pełnomocnik (Proxy) – zastępca, który kontroluje dostęp do prawdziwego obiektu"},{"id":"6b08bd3280884893657cc938","slug":"decorator","title":"Dekorator (Decorator) – dokładanie zachowania warstwa po warstwie"},{"id":"6b08bd3180884893657cc91a","slug":"composite","title":"Kompozyt (Composite) – drzewa, w których liść i gałąź wyglądają tak samo"},{"id":"6b08bd2f80884893657cc8de","slug":"adapter","title":"Adapter – jak dogadać się z kodem, który mówi innym językiem"}],"topicsInfo":[{"slug":"decorator","title":"Dekorator","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"}