JavaScript debouncing and throttling

Debouncing

Within a given time period, events are frequently triggered, but only the last one is executed. This is achieved using a timer at the underlying level.

  • lodash implementation

Use the _.debounce() function

grammar:

_.debounce(fun, time)

  mouse.addEventListener('mousemove',_.debounce(mouseMove,100))
  • Handwritten implementation

Core idea: Implement using the delay function (setTimeout).

  1. Declare timer variables
  2. Each time an event is triggered, check if there is a timer; if so, clear the previous timer first.
  3. Turn on the timer
    let time
function mouseMove()
{
if(time)
{
clearTimeout(time)
}
time = setTimeout(function(){
n+=1
mouse.innerHTML=n
},1000)
}
mouse.addEventListener('mousemove',mouseMove)

Throttling

Events are frequently triggered within a unit of time, but are executed only once.

Often used for high-frequency events such as: mousemove, resize, scroll

The difference between debouncing and throttling: Both deal with frequently triggered events, but debouncing only executes after a set time period when the event stops triggering, meaning it pauses for a certain time before executing. Throttling, on the other hand, executes only once within a set time period and does not require pausing.

  • lodash implementation
    mouse1.addEventListener("mousemove",_.throttle(function(){
      m+=1
      mouse1.innerHTML=m
    },500))
  • Implemented by hand

Similarly, the setTimeOut function is used.

    let time1
    mouse1.addEventListener("mousemove",function(){
      if(time1==0)
    {
      return
    }
    else
    {
      time1 = setTimeout(function(){
        m+=1
        mouse1.innerHTML=m
        time1=1
      },500)
      time1=0
    }
    })