Home Web Front-end JS Tutorial Detailed explanation of what debounce is in JS functions?

Detailed explanation of what debounce is in JS functions?

Jun 22, 2018 pm 03:54 PM

This article mainly introduces the detailed analysis of JS function debouncing and throttling related knowledge and code analysis. Friends who need it can refer to it.

This article starts with the basic knowledge of the concepts of throttling and debouncing, and conducts a detailed analysis of JS functions. Let’s take a look at:

1. What is throttling? Streaming and debounce?

Throttling. Just tighten the faucet to make the water flow less, but it doesn't stop the water flow. Imagine that sometimes in real life we ​​need to pick up a bucket of water. While picking up the water, we don’t want to stand there waiting all the time. We may have to leave for a while to do something else, so that the water can almost fill the bucket. When you come back again, you can't open the faucet too high, otherwise the water will be full before you come back, and a lot of water is wasted. At this time, you need to throttle down so that the water is almost full when you come back. So is there such a situation in JS? A typical scenario is lazy loading of images and monitoring the scoll event of the page, or monitoring the mousemove event of the mouse. The corresponding processing methods of these events are equivalent to water, because scroll and mousemove are used when the mouse moves. It will be triggered frequently by the browser, which will cause the corresponding events to be triggered frequently (the water flow is too fast), which will cause a lot of browser resource overhead, and a lot of intermediate processing is unnecessary. It will cause the browser to freeze. At this time, it is necessary to throttle. How to throttle? We cannot prevent the browser from triggering the corresponding event, but we can reduce the execution frequency of the methods that handle the event, thereby reducing the corresponding processing overhead.

Debounce. I probably first came across this term in high school physics. Sometimes the switch may jitter before it is actually closed. If the jitter is obvious, the corresponding small light bulb may flash. It doesn't matter if the light bulb flashes out. , it will be troublesome if the eyes are damaged again. At this time, a debounce circuit will appear. In our page, this situation also occurs. Suppose that one of our input boxes may query the corresponding associated words in the background while inputting content. If the user inputs at the same time, input events are frequently triggered, and then frequently backwards. If the request is raised, the previous requests should be redundant until the user input is completed. Assuming that the network is slower and the data returned by the background is slower, the associated words displayed may change frequently until the last request is returned. . At this time, you can monitor whether to input again within a certain period of time. If there is no input again, it will be considered that the input is completed and the request will be sent. Otherwise, it will be judged that the user is still typing and the request will not be sent.

Debounce and throttling are different, because although throttling limits the intermediate processing functions, it only reduces the frequency, while debounce filters out all the intermediate processing functions and only executes the rules. The last event within the determination time.

2. JS implementation.

I’ve covered so much before, thank you for your patience in reading this. Next, let’s take a look at how to achieve throttling and debounce.

Throttling:

/** 实现思路:
  ** 参数需要一个执行的频率,和一个对应的处理函数,
  ** 内部需要一个lastTime 变量记录上一次执行的时间
  **/
  function throttle (func, wait) {
   let lastTime = null    // 为了避免每次调用lastTime都被清空,利用js的闭包返回一个function确保不生命全局变量也可以
   return function () {
    let now = new Date()
    // 如果上次执行的时间和这次触发的时间大于一个执行周期,则执行
    if (now - lastTime - wait > 0) {
     func()
     lastTime = now
    }
   }
  }
Copy after login

Let’s look at how to call:

// 由于闭包的存在,调用会不一样
let throttleRun = throttle(() => {
  console.log(123)
}, 400)
window.addEventListener('scroll', throttleRun)
Copy after login

At this time, if f scrolls the page crazily, you will find that a 123 will be printed in 400ms, but without throttling, it will Print continuously, you can change the wait parameter to feel the difference.

But up to this point, our throttling method is imperfect because our method does not obtain the this object when the event occurs, and because our method simply and crudely determines the time and date of the trigger. The interval between execution times is used to determine whether to execute the callback. This will cause the last trigger to be unable to be executed, or the user's departure interval is indeed very short and cannot be executed, resulting in manslaughter, so the method needs to be improved.

function throttle (func, wait) {
   let lastTime = null
   let timeout
   return function () {
    let context = this
    let now = new Date()
    // 如果上次执行的时间和这次触发的时间大于一个执行周期,则执行
    if (now - lastTime - wait > 0) {
     // 如果之前有了定时任务则清除
     if (timeout) {
      clearTimeout(timeout)
      timeout = null
     }
     func.apply(context, arguments)
     lastTime = now
    } else if (!timeout) {
     timeout = setTimeout(() => {
      // 改变执行上下文环境
      func.apply(context, arguments)
     }, wait)
    }
   }
  }
Copy after login

In this way, our method is relatively complete, and the calling method is the same as before.

Debounce:

The debounce method is consistent with throttling, but the method will only be executed after the jitter is determined to be over.

debounce (func, wait) {
   let lastTime = null
   let timeout
   return function () {
    let context = this
    let now = new Date()
    // 判定不是一次抖动
    if (now - lastTime - wait > 0) {
     setTimeout(() => {
      func.apply(context, arguments)
     }, wait)
    } else {
     if (timeout) {
      clearTimeout(timeout)
      timeout = null
     }
     timeout = setTimeout(() => {
      func.apply(context, arguments)
     }, wait)
    }
    // 注意这里lastTime是上次的触发时间
    lastTime = now
   }
  }
Copy after login

At this time, call it in the same way as before. You will find that no matter how crazy you scroll the window, the corresponding event will only be executed when you stop scrolling.

Debounce and throttling have been implemented in many mature js, and the general idea is basically this.

Let’s share with you the code of the netizen’s implementation method:

Method 1

1. The idea of ​​​​this implementation method is easy to understand. : Set an interval time, such as 50 milliseconds, and set the timer based on this time. When the interval between the first trigger event and the second trigger event is less than 50 milliseconds, clear this timer and set a new timer. , and so on, until there is no repeated trigger within 50 milliseconds after an event is triggered. code show as below:

function debounce(method){ 
 clearTimeout(method.timer); 
 method.timer=setTimeout(function(){ 
  method(); 
 },50); 
}
Copy after login

这种设计方式有一个问题:本来应该多次触发的事件,可能最终只会发生一次。具体来说,一个循序渐进的滚动事件,如果用户滚动太快速,或者程序设置的函数节流间隔时间太长,那么最终滚动事件会呈现为一个很突然的跳跃事件,中间过程都被节流截掉了。这个例子举的有点夸张了,不过使用这种方式进行节流最终是会明显感受到程序比不节流的时候“更突兀”,这对于用户体验是很差的。有一种弥补这种缺陷的设计思路。

方法二

2.第二种实现方式的思路与第一种稍有差别:设置一个间隔时间,比如50毫秒,以此时间为基准稳定分隔事件触发情况,也就是说100毫秒内连续触发多次事件,也只会按照50毫秒一次稳定分隔执行。代码如下:

var oldTime=new Date().getTime(); 
var delay=50; 
function throttle1(method){ 
 var curTime=new Date().getTime(); 
 if(curTime-oldTime>=delay){ 
  oldTime=curTime; 
  method(); 
 } 
}
Copy after login

相比于第一种方法,第二种方法也许会比第一种方法执行更多次(有时候意味着更多次请求后台,即更多的流量),但是却很好的解决了第一种方法清除中间过程的缺陷。因此在具体场景应根据情况择优决定使用哪种方法。

对于方法二,我们再提供另一种同样功能的写法:

var timer=undefined,delay=50; 
function throttle2(method){ 
 if(timer){ 
  return ; 
 } 
 method(); 
 timer=setTimeout(function(){ 
  timer=undefined; 
 },delay); 
}
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在vue-cli中如何实现移动端自适应

在Webpack中如何加载SVG

webpack打包配置(详细教程)

在Javascript中自适应处理方法

The above is the detailed content of Detailed explanation of what debounce is in JS functions?. 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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1673
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

Python vs. JavaScript: Use Cases and Applications Compared Python vs. JavaScript: Use Cases and Applications Compared Apr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

See all articles