What is Debouncing?
Nick Scialli
September 07, 2020
Debouncing is a concept in programming in which you defer the execution of some code after a certain amount of inactivity time.
Let’s say we want to auto-save a user’s work as they type. However, we don’t want to send a save request every single keystroke—this would potentially be very expensive. Instead, we can decide to wait for a few seconds of inactivity and then send a save request.
How to Implement Debouncing
We can use pseudocode to implement debouncing in our “auto-saving” use case. Here’s how that might look if we want to save after two seconds of inactivity.
createDebounceTimer:
saveTextAfterTwoSeconds
onTextBoxChange:
cancelTimerIfExists
setNewTimerWithCurrentText
And we can implement this pretty quickly in HTML/JavaScript.
<body>
<input id="my-input" />
<p id="debounced-content"></p>
<script>
let debounceTimer;
const myInput = document.querySelector('#my-input');
const debouncedContent = document.querySelector('#debounced-content');
myInput.addEventListener('keydown', function (e) {
if (debounceTimer) {
clearTimeout(debounceTimer);
}
debounceTimer = setTimeout(function () {
debouncedContent.innerHTML = e.target.value;
}, 2000);
});
</script>
</body>
Let’s take a peek at this in action!
Success, we have implemented debouncing in HTML and JavaScript!
Debounce vs. Throttling
A similar concept you might have heard of is throttling. Throttling is different than debouncing: throttling will perform a task every X seconds, regardless of activity. In JavaScript, you can think of this as using a setInterval
that we never clear instead of a setTimeout
that we do clear. While implementing throttling is outside the scope of this article, it’s important to keep in mind the difference between these to methods!
Nick Scialli is a senior UI engineer at Microsoft.