“Debounce” is handy for kicking off searches when a user finishes typing in a search field. You can implement it in Javascript with the following simple snippet:

let debounceTimeoutId = null // Put this wherever you deem appropriate.
function debounce() {
    if (debounceTimeoutId) {
    debounceTimeoutId = setTimeout(function() {
        // ... kick off your search request here.
    }, 500) // Half a second is a good rule of thumb.
// ... call debounce whenever your search field changes, as per your UI framework.


Lately I’ve been implementing a lot of search screens for a backoffice management system, trying to keep the interface clear and simple, while trying to fit everything on the screen without resorting to scrolling. And the ubiquitious ‘search’ button was on the chopping block. But how?

It turns out, a nice user interface for searching is simply to have the one text field with ‘search’ as the placeholder text, axe the search button, and automatically perform the search when the user stops typing. And the appropriate algorithm for detecting when users stop typing is called the ‘debounce’, which you can read more about here.

The gist of it is that if the user stops typing for a given time, it kicks off the search. Or if the user starts typing again before that timeout, the timer starts again. So if you type one character every 0.4s for an hour, it’ll never search until you’re finished - that’s the idea.

But I don’t want to bring RxJS into my project for one small feature, as I try to avoid as many dependencies as reasonably possible in the aim to keep my codebase efficient. And so here we have my simplest implementation of debounce above in the TL;DR section.

The only thing to be aware of is that you have to store the timeout ID somewhere. If you’re using something similar to React (Mithril.js in my case), your component is a good place to store it. If you’re writing vanilla JS, then maybe you can YOLO it into the window object :) It’s up to you to find the appropriate place for it.

Thanks for reading, I hope this helps someone, and have a great week!

Photo by Samuel Elias on Unsplash

Thanks for reading! And if you want to get in touch, I'd love to hear from you: chris.hulbert at gmail.

Chris Hulbert

(Comp Sci, Hons - UTS)

iOS Developer (Freelancer / Contractor) in Australia.

I have worked at places such as Google, Cochlear, Assembly Payments, News Corp, Fox Sports, NineMSN, FetchTV, Coles, Woolworths, Trust Bank, and Westpac, among others. If you're looking for help developing an iOS app, drop me a line!

Get in touch:
[email protected]

 Subscribe via RSS