Detailed analysis of JS function debouncing and throttling
1. What are throttling and debouncing?
Throttling. Just tighten the faucet to make the water flow less, but it doesn't stop the 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.
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 } } }
Let’s see how to call:
// 由于闭包的存在,调用会不一样 let throttleRun = throttle(() => { console.log(123) }, 400) window.addEventListener('scroll', throttleRun)
At this time, if you scroll the page crazily, you will find that a 123 will be printed in 400ms. If there is no throttling, it will be printed 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) } } }
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 } }
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 us 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 from the first trigger event to 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. The code is as follows:
function debounce(method){ clearTimeout(method.timer); method.timer=setTimeout(function(){ method(); },50); }
There is a problem with this design method: an event that should be triggered multiple times may end up happening only once. Specifically, for a gradual scrolling event, if the user scrolls too fast, or the function throttling interval set by the program is too long, the final scrolling event will appear as a sudden jump event, and the intermediate process will be cut off by throttling. . This example is a bit exaggerated, but if you use this method to throttle, you will eventually feel that the program is "more abrupt" than when it is not throttled, which is very poor for the user experience. There is a design idea to make up for this shortcoming.
Method Two
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(); } }
相比于第一种方法,第二种方法也许会比第一种方法执行更多次(有时候意味着更多次请求后台,即更多的流量),但是却很好的解决了第一种方法清除中间过程的缺陷。因此在具体场景应根据情况择优决定使用哪种方法。
对于方法二,我们再提供另一种同样功能的写法:
var timer=undefined,delay=50; function throttle2(method){ if(timer){ return ; } method(); timer=setTimeout(function(){ timer=undefined; },delay); }
以上内容就是JS函数去抖和节流详解,希望能帮助到大家。
相关推荐:
The above is the detailed content of Detailed analysis of JS function debouncing and throttling. For more information, please follow other related articles on the PHP Chinese website!

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)