【问题标题】:Debounced function calls delayed but all executed when wait timer ends去抖函数调用延迟但在等待计时器结束时全部执行
【发布时间】:2017-03-14 01:31:04
【问题描述】:

我正在使用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)"
  >

这是我的控制台日志:

【问题讨论】:

    标签: javascript vue.js debouncing


    【解决方案1】:

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

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

    【讨论】:

    • 是的,您可以,我刚刚在文档vuejs.org/guide/… 中阅读过它。谢谢!但是您的语法有点错误,您可以检查一下文档并纠正一下,以便我可以√?
    • 语法很好。这一切都取决于你想如何处理它。我将更新我的示例以处理参数。
    • 那么我之前所做的事情发生了什么?
    • 您正在创建一堆不同的debounced 函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    相关资源
    最近更新 更多