0

I am attempting to implement a search and have an input were a user types in a search term and every 1.5 seconds i want it to hit the endpoint to get the search results. Right now I have an input like this

<input v-model="term" type="text" class="form-control" placeholder="Search"
           v-on:input="search($event.target.value)" @focusin="enableSearch" @focusout="clear">

The I have a function that is throttled using lodash throttle method to call the endpoint.

search: _.throttle(function (term) {
        if (this.term != null && this.term.length > 3) {
            this.toggleSearch();
            this.searchQueue(term)
        }
    }, 1500),

now when i type in a search term like "Joe D" instead of getting one call to the endpoint i get 4. It looks like i get a endpoint call for each key press.

Not sure why the throttling is not working. Any help would be appreciated.

John
  • 31
  • 1
  • 5
  • 1
    Tried to [recreate your example](https://codepen.io/genechk/pen/jOrKzdo) and it appears to be working. – genechk Nov 03 '20 at 21:36

1 Answers1

1

You may want debounce instead of throttle.

Throttle is more about spacing out events per time frame, while debounce is about combining multiple events into one.

Here is a nice demo that illustrates the difference and you can read more here.

Dan
  • 59,490
  • 13
  • 101
  • 110
  • I tried both and instead of getting one call i am getting 4 – John Nov 03 '20 at 20:46
  • Are you typing slower than the 1.5s debounce rate? If yes-- that's why. If no-- you're possibly doing something counterproductive in `searchQueue` or some other method which isn't shown. Here is a simple [demo](https://jsfiddle.net/sh0ber/2yejmLp8/) – Dan Nov 03 '20 at 20:59
  • The throttle method runs once but for some reason my axios call is running multiple times – John Nov 04 '20 at 19:09
  • Sounds like throttle is completely unrelated to the issue. Time to add the relevant code to your question. – Dan Nov 04 '20 at 19:19
  • Revisiting old questions, I see that you never added `searchQueue` or `toggleSearch` code to see why it's running multiple times. – Dan Nov 17 '20 at 17:20