去抖动函数调用延迟但在等待计时器结束时全部执行

时间:2016-10-31 21:48:46

标签: javascript vue.js debouncing

我正在使用debounce来实现“当您键入时搜索”字段。

我正在阅读https://css-tricks.com/debouncing-throttling-explained-examples/,根据我的理解,该功能应该只被调用有限次数。

在我的情况下,函数调用被延迟,但是等待计时器结束后立即执行:

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
    })
  },

HTML(它是Vue.JS)

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

这是我的console.log:console

1 个答案:

答案 0 :(得分:1)

每次keydown时你都会创建一个限制函数(顺便说一句,你应该使用input)。你可以这样做,我认为......

methods: {
  searchOnType: throttle((currentPage, searchString) => {
    this.getMovies('movies.json', currentPage, searchString)
  }, 1000, {leading: false, trailing: true})
}