1. Home
  2. Blog
  3. Software Development

Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Typing, scrolling and resizing fire events dozens of times a second. Debounce and throttle stop your code from running on every one of them, in two very different ways. We timed both in Node.js to show exactly what each does.

10 min read
Debounce vs throttle in JavaScript: how they work, when to use each, tested

Key takeaways

  • Debounce waits until events stop for a set time, then runs once. Good for search boxes and auto-save.
  • Throttle runs at most once per interval while events keep coming. Good for scroll and resize.
  • In our test, 8 keystrokes caused 1 debounced search, and 51 scroll events caused 5 throttled updates.
  • Throttle with a trailing call makes sure the final event, such as the last scroll position, is handled.

A search box calls an API on every keystroke. Typing “pen stand” sends nine requests, eight of which are useless, and the results may even arrive out of order. A scroll handler recalculates layout sixty times a second and the page stutters. Debounce and throttle are the two standard fixes, and choosing the wrong one creates its own bugs.

We wrote small implementations of both and fed them simulated events in Node.js 24, recording when each function actually ran. Timer precision varies by system, so your milliseconds will differ slightly, but the pattern will not.

The short answer

Debounce Throttle
Runs Once, after events stop Regularly, during events
Rule “Wait until the user stops” “At most once every N ms”
Feels Calm, final Responsive, continuous
Typical use Search, validation, auto-save, resize end Scroll, mouse move, drag, live progress
Risk Never runs during constant input Can miss the final event

Why limit events at all?

Browsers fire input events on every keystroke, and scroll, mousemove and resize events many times per second. If each handler does real work, such as an API call, a heavy calculation or a layout read, the page wastes battery, floods the server and feels slow. Limiting how often the handler runs keeps the interface smooth and the backend calm. On the server side, the equivalent protection is API rate limiting.

How debounce works

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

Every call cancels the previous timer and starts a new one. The function only runs when a full wait period passes with no new calls. The variable t survives between calls because of a closure, which is what makes this short implementation work.

Debounce test: a search box

We simulated typing “pen stand” as 8 keystrokes, 80 ms apart, with a 300 ms debounce:

const search = debounce((q) => calls.push(`search("${q}")`), 300);
for (const q of ["p","pe","pen","pen ","pen s","pen st","pen sta","pen stand"]) {
  search(q);
  await sleep(80);
}

// debounce: 8 keystrokes 80ms apart -> 1 call(s) [ ' 904ms search("pen stand")' ]

One search ran, with the complete text, about 300 ms after the last keystroke. Without debouncing, there would have been eight requests. A good wait for typing is usually 200 to 500 ms: short enough to feel instant, long enough to skip most intermediate keystrokes.

Tip: Debouncing reduces requests, but it does not stop slow responses arriving out of order. If an older search finishes after a newer one, the screen shows stale results. Cancel the previous request with AbortController, or ignore responses that are not for the latest query. Our Fetch API guide shows how.

When debounce never fires

Debounce has a sharp edge. We called a 300 ms debounced function every 100 ms for 1.5 seconds:

debounce during 1.5s of constant input: fired 0 times
after input stops: fired 1

As long as events keep arriving faster than the wait, the timer keeps resetting and the function never runs. For a search box that is fine. For a live progress display or an auto-save during a long typing session, it is a bug: nothing is saved until the user pauses. Lodash’s debounce offers a maxWait option for exactly this, forcing a call at least every so often.

How throttle works

function throttle(fn, wait) {
  let last = -Infinity;
  return (...args) => {
    const now = Date.now();
    if (now - last >= wait) {
      last = now;
      fn(...args);
    }
  };
}

The first call runs immediately. Calls during the next wait milliseconds are ignored. After that, the next call runs, and so on. The function runs at a steady maximum rate for as long as events keep coming.

Throttle test: scrolling

We simulated scrolling from position 0 to 1000 in steps of 20, about every 16 ms, which is 51 events, with a 200 ms throttle:

throttle (leading only): 51 events -> 5 calls [ 0, 240, 460, 660, 860 ]

Instead of 51 updates, the handler ran 5 times, spread evenly through the scroll. But look at the last value: 860. The scroll ended at 1000, and that final position was never handled. For something like a “back to top” button that should appear at the bottom of the page, this is a real bug.

Leading and trailing calls

The fix is a trailing call: if events were ignored during the last interval, run once more at the end with the latest arguments. We tested a version with both leading and trailing calls on the same scroll:

throttle (leading+trailing): -> 7 calls, last value 1000

Now the final position, 1000, was handled. The same idea applies to debounce in reverse: a leading debounce runs on the first event and then ignores the burst, which suits buttons that should react instantly but must not be double-clicked.

Variant Behaviour Example
Debounce, trailing (default) Run after the burst ends Search as you type
Debounce, leading Run at the start, ignore the rest of the burst Prevent double submit
Throttle, leading Run immediately, then at most once per interval Scroll position
Throttle, leading + trailing As above, plus one final call Scroll or resize with correct end state

Which to use where

  • Search suggestions, filtering a list: debounce, 200 to 400 ms.
  • Form field validation: debounce, so errors do not flash while the user is still typing.
  • Auto-save: debounce with a maximum wait, so long sessions still save.
  • Window resize recalculation: debounce if you only need the final size, throttle if the layout must follow along.
  • Infinite scroll, scroll-spy, sticky headers: throttle with a trailing call.
  • Mouse move, drag, game input: throttle, or requestAnimationFrame for visual updates.
  • Analytics events: throttle, to cap the volume sent.

Libraries and frameworks

Our implementations are minimal teaching versions. Production code needs cancellation, flushing, correct this handling and edge cases around timers. Lodash’s debounce and throttle are the common choice and support leading, trailing and maxWait options, plus cancel() and flush() methods.

In React, create the debounced function once, for example with useMemo or useRef, rather than on every render. A new debounced function per render has its own new timer, so nothing is ever debounced. Cancel pending calls when the component unmounts, or a late call may update state that no longer exists.

requestAnimationFrame for visual updates

For work that only changes what is drawn, such as moving an element with the mouse, browsers offer a better throttle: requestAnimationFrame. It runs your code right before the next screen repaint, usually 60 times a second, and pauses in background tabs. Store the latest event data, and schedule at most one frame callback at a time. Use time-based throttling for things that are not about drawing, such as network calls.

Testing timing code

Real timers make tests slow and flaky. Our demo took several seconds because it really waited. In a test suite, use fake timers instead: Jest and Vitest both provide them, letting a test call the debounced function, advance the clock by 299 ms and assert nothing happened, then advance 1 ms more and assert one call. Test the edge cases: a single call, a burst, a continuous stream longer than the wait, and cancellation. Those are exactly where our measurements showed surprising behaviour.

Final thoughts

Debounce waits for quiet; throttle keeps a steady pace. Use debounce when only the final value matters, such as a search term, and throttle when the user needs continuous feedback, such as scrolling. Add a trailing call to throttle so the last event is never lost, add a maximum wait to debounce for long sessions, and prefer a well-tested library in production.

Frequently asked questions

What is the difference between debounce and throttle?

Debounce runs a function once after events stop for a set time. Throttle runs it at most once per interval while events continue. In our test, debounce turned 8 keystrokes into 1 call and throttle turned 51 scroll events into 5.

When should I use debounce?

When only the final value matters, such as search-as-you-type, form validation, auto-save or the end of a window resize.

When should I use throttle?

When the user needs regular feedback during continuous activity, such as scrolling, dragging, mouse movement or progress updates.

Why does my debounced function never run?

If events keep arriving faster than the wait time, the timer keeps resetting. Add a maximum wait, as Lodash’s maxWait option does, or use throttle instead.

What is a trailing call in throttle?

A final call made at the end of the interval with the most recent arguments, so the last event is handled. Without it, our test missed the final scroll position.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →