Best way to throttle a "live" search input?


I have a react search input that fires during onChange and stores the new value in a session value, which is passed into a subscription. The collection has 3M+ records and this is going kind of slow… it is basically re-firing the subscription on every keystroke.

I’m guessing the easiest thing to do is throttle the input a little?

Then another improvement may be somehow cancelling the subscription call if the user is still typing?


Can expand this answer if required but basically: or depending on whether you use underscore or lodash :slight_smile:


Thanks! I actually don’t use either at this point but used lodash in the past (hipster told me it isn’t cool to use underscore).

I’ll see if I can get this goin. My function is literally this basic right now:

    Session.set("searchValue", {title:}); // stores text value onChange
    Session.set('isLoading', true); // shows spinner, then reset to false once subscription is done re-running

I see these:


Remember that Meteor uses underscore so the _ object should be available in your Meteor code. I have a feeling it’s a fairly old version they’re running though. Underscore is a good option but you may need to a _.noConflict() statement immediately after requiring/importing it to avoid conflicting with Underscore.


you think this?

import _ from 'meteor/underscore'

this isn’t doing the trick unfortunately:

    let searchString =;
    const doSearch = () => {
      Session.set("searchValues_companies", {title: searchString});
      Session.set('isLoading', true);
    _.debounce(doSearch, 500);


This worked:

import {debounce} from 'throttle-debounce';

this.doSearch = debounce(500, this.doSearch);
       Session.set("searchValue", {title: searchString});
      Session.set('isLoading', true);


thanks for you time time @mjmasn



const doSearch = (searchString) => {
    Session.set("searchValues_companies", {title: searchString});
    Session.set('isLoading', true);

const debouncedSearch = _.debounce(doSearch, 500);


EDIT: You beat me to it, for clarity the issue with your original code was that you were redefining the debounced function every time it was called, so it never actually debounced. Always make sure you define the debounced function outside of the function that’s calling it.


Awesome, I wouldn’t have even thought of using debounce for this. I’ve been manually creating a timer via setTimeout to wait after a keystroke before searching. :thumbsup: