Table of Contents
Throttling
Debounce
Home Web Front-end JS Tutorial Detailed introduction to debouncing and throttling in JavaScript (code example)

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

Jan 11, 2019 am 10:10 AM
html javascript

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()">
Copy after login

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)
})
Copy after login

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)
      }
    }
  }
}
Copy after login

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)
    }
  }
}
Copy after login

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()
  }
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles