0

I am using debounce in order to implement a 'search as you type' field.

I am reading https://css-tricks.com/debouncing-throttling-explained-examples/ and from what I can understand the function should only be called a limited number of times.

In my case, the function calls are delayed, but executed all at once once the wait timer ends:

methods: {
  searchOnType: function (currentPage, searchString) {
    console.log(`Searching ${searchString}`)
    var debounced = throttle(this.getMovies, 4000, {leading: false, trailing: true})
    debounced('movies.json', currentPage, searchString)
  },
  getMovies: function (url, page, query) {
    console.log(query)
    this.loading = true
    resourceService.getMovies(url, page, query).then((result) => {
      this.items = result.movies
      this.totalMovies = result.total
      this.loading = false
    })
  },

the HTML (it's Vue.JS)

  <input 
    type="text" 
    v-model="searchString" 
    class="form-control input-lg" 
    placeholder="search movie" 
    @keydown="searchOnType(currentPage, searchString)"
  >

This is my console.log:console

George Katsanos
  • 13,524
  • 16
  • 62
  • 98

1 Answers1

2

You're creating a throttled function every time you keydown (you should probably be using input instead by the way). You can do this instead I think...

methods: {
  searchOnType: throttle((currentPage, searchString) => {
    this.getMovies('movies.json', currentPage, searchString)
  }, 1000, {leading: false, trailing: true})
}
Bill Criswell
  • 32,161
  • 7
  • 75
  • 66