javascript
25 lines · 6 steps
Building a debounce function in JavaScript
A closure remembers a pending timer so a function only fires after calls stop arriving.
Explained by
highlit
1function debounce(fn, delay) {
2 let timeoutId = null;
3
4 function debounced(...args) {
5 const context = this;
6
7 if (timeoutId !== null) {
8 clearTimeout(timeoutId);
9 }
10
11 timeoutId = setTimeout(() => {
12 timeoutId = null;
13 fn.apply(context, args);
14 }, delay);
15 }
16
17 debounced.cancel = function () {
18 if (timeoutId !== null) {
19 clearTimeout(timeoutId);
20 timeoutId = null;
21 }
22 };
23
24 return debounced;
25}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A closure over timeoutId lets each debounced function privately track its own pending timer.
- 2Clearing the previous timer on every call ensures fn only runs once activity pauses for delay ms.
- 3Capturing this and args at call time, then replaying them via apply, preserves the original calling context.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-debounce-function-in-javascript-explained-javascript-8266/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.