Image stabilization function and a throttle function (the interface call frequency limit)

I. stabilization function and a throttle function

  • The concept :( same effect -> limit how often the task is triggered)
    • Anti-shake function debounce: within a specific period of time, there is no specific trigger conditions to perform a task
    • Throttling function throttle: within a specific period of time, regardless of the trigger conditions several times, only to perform a mission
  • the difference:
    • Anti-shake function it is possible for a long time is not a task execution, only last execution after a delay has elapsed time
    • Fixed throttle function will trigger a task at a given time, and is a regular
  • Scenario:
    • Keyword search, limit call frequency interfaces (anti-shake)
    • Form validation, verification mailbox format, stop doing input validation (anti-shake)
    • onresize onscroll onmousemove (throttle) ---> for high-frequency events do trigger the display frequency

II. Frequency to prevent transmission request (image stabilization)

// 函数防抖(固定时间内没有触发条件,就执行一次任务)
inputHandle () {
  clearTimeout(this.timer)
  this.timer = setTimeout(async () => {
    let res = await request('goods/qsearch', 'get', {
      query: this.keyword
    })
    this.searchResult = res.data.message
  }, 1000)
}
复制代码

PREVENTION OF frequency (throttle) transmission request

// 函数节流(固定时间内无论触发几次,仅执行一次任务)
keywordSearch () {
  if (this.isLoading) {
    // 终止后续代码的执行,终止请求
    return
  }
  this.isLoading = true
  setTimeout(async () => {
    let res = await request('goods/qsearch', 'get', {
      query: this.keyword
    })
    this.searchResult = res.data.message
    // 重新打开发送请求的开关
    this.isLoading = false
  }, 1000)
}
复制代码

Reproduced in: https: //juejin.im/post/5d07ae20e51d45590a445b36

Guess you like

Origin blog.csdn.net/weixin_33953384/article/details/93179075