python
39 lines · 6 steps
A thread-safe debounce decorator in Python
A decorator that delays a function until calls stop arriving, using a lock and a restartable timer.
Explained by
highlit
1import threading
2from functools import wraps
3
4
5def debounce(wait):
6 def decorator(fn):
7 lock = threading.Lock()
8 state = {"timer": None}
9
10 @wraps(fn)
11 def wrapper(*args, **kwargs):
12 def call():
13 with lock:
14 state["timer"] = None
15 fn(*args, **kwargs)
16
17 with lock:
18 if state["timer"] is not None:
19 state["timer"].cancel()
20 state["timer"] = threading.Timer(wait, call)
21 state["timer"].daemon = True
22 state["timer"].start()
23
24 def cancel():
25 with lock:
26 if state["timer"] is not None:
27 state["timer"].cancel()
28 state["timer"] = None
29
30 wrapper.cancel = cancel
31 return wrapper
32
33 return decorator
34
35
36@debounce(0.3)
37def on_search_input(query):
38 results = search_index.query(query)
39 render(results)
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Debouncing collapses a burst of rapid calls into one execution after the activity settles.
- 2A shared mutable dict plus a lock lets nested closures coordinate state safely across threads.
- 3Attaching a method to the returned wrapper extends a decorated function without changing its signature.
Related explainers
rust
use axum::{ extract::State, http::StatusCode, Json,
Idempotent webhook handling in Axum
deduplication
idempotency
shared-state
Intermediate
8 steps
php
<?php namespace App\Services;
Tagged cache invalidation in Laravel
caching
cache-tags
invalidation
Intermediate
5 steps
go
package middleware import ( "log"
Per-IP rate limiting middleware in Gin
rate-limiting
middleware
concurrency
Intermediate
8 steps
python
from urllib.parse import urlparse, parse_qs from dataclasses import dataclass, field ALLOWED_SCHEMES = {"http", "https"}
Validating URLs into a safe endpoint in Python
input validation
url parsing
dataclasses
Intermediate
7 steps
javascript
const crypto = require('crypto'); function inMemoryCache({ maxAge = 60_000, maxEntries = 500 } = {}) { const store = new Map();
Building an in-memory cache middleware in Express
caching
middleware
etag
Advanced
10 steps
java
@Component public class InventoryReconciliationJob { private static final Logger log = LoggerFactory.getLogger(InventoryReconciliationJob.class);
Distributed scheduled jobs with Spring locks
distributed-locking
scheduling
concurrency
Advanced
8 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/a-thread-safe-debounce-decorator-in-python-explained-python-17eb/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.