Home  >  Article  >  Web Front-end  >  Detailed introduction to debouncing and throttling in JavaScript (code example)

Detailed introduction to debouncing and throttling in JavaScript (code example)

不言
不言forward
2019-01-11 10:10:082853browse

This article brings you a detailed introduction (code example) about debouncing and throttling in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Whether it is an interview or discussing browser optimization, the issues of debouncing and throttling will be involved.
In general, these two are a way to limit the frequency of event triggering. The difference is that throttling specifies the time interval when events are triggered; debouncing specifies the time intervals when events are not triggered. Judging from the results, throttling reduces the sensitivity of time processing; while debounced, the triggering events are stored first, and then sent together after the specified event interval exceeds.
Getting more and more dizzy, go directly to the code:
HTML

<input type="text" oninput="fatch()">

There is an input tag for users to search, and there is a processing function catch that will be triggered by the input event. , this catch will request associated words from the background based on the value of the input.
There is no problem with the above code idea, but if there are no trigger restrictions, a large number of http requests may be generated, and many of these requests may not be of much significance, providing space for our optimization; below, I will use Two ideas, throttling and debouncing, are used to solve this problem. (Generally for input situations, debounce is used; this is just for convenience of code explanation)

Throttling

function jieliu (func, time){//func 执行函数, time 时间间隔
  let lastRun = null
  
  return function(){
    const now = new Date()
    if(now - lastRun > time){
      func(...arguments)
      lastRun = now
    }
  }
}


const listener = jieliu(function(value){//监听函数,指定间隔时间
  console.log(value)
}, 1000)

const input = document.querySelector("input")
//调用方法
input.addEventListener("input", function(event){
     listener(event.target.value)
})

The above is a relatively simple throttling implementation and basic calling method; use The closure is to save the lastRun of each execution. The requirement to limit the frequency of requests is basically implemented, but the triggering of the last one is ignored.
Improvements are as follows:

function jieliu (func, time){// 触发时间间隔>time 发送请求
  let lastRun = null
  let timeout = undefined
  return function(){
    const self = this; 
    const now = new Date()
    if(now - lastRun > time){
      if(timeout){
        clearTimeout(timeout)
        timeout = undefined
      }
      func.apply(self, arguments)
      lastRun = now
    }
    else{
      if(!timeout){
        timeout = setTimeout(func.apply(self, arguments), time)
      }
    }
  }
}

Add timeout to determine whether it is the last request.

Debounce

function qudou(func, time){
  let timeout = undefined
  
  return function(){
    const argu = arguments
    const self = this

    if(timeout){
      clearTimeout(timeout)
      timeout = undefined
    }else{
        timeout = setTimeout(func.apply(this, arguments), time)
    }
  }
}

The above is a simple implementation of debounce. Similarly, the last event cannot trigger the processing function.

Improvements are as follows:

function qudou(func, time){//判断连续time时间内不触发,发送func请求
  let timeout = undefined;
  let lastRun = null
  return function(){
    const self = this
    const now = new Date()
    if(now - lastRun > time){
      func.apply(self, arguments)
    }
    else {
      if(!timeout){
        timeout = setTimeout(func.apply(self, arguments), time)
      }
      else {
        clearTimeout(timeout)
        timeout = undefined
      }
    }
    lastRun = new Date()
  }
}

Summary

Write down the whole article. The main way to achieve throttling is by comparing "now" and "lastRun" time difference, thereby reducing the number of calls to the processing function; anti-shake still uses settimeout to delay the calling timing of the processing function, and then summarizes the results of multiple triggers and calls the processing function together.


The above is the detailed content of Detailed introduction to debouncing and throttling in JavaScript (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete