In the browser DOM events, there are some events that will be triggered continuously along with the user's operations. For example: resize the browser window (resize), scroll the browser page (scroll), and move the mouse (mousemove). That is to say, when the user triggers these browser operations, if the corresponding event processing method is bound to the script, this method will be triggered continuously.
This is not what we want, because sometimes if the event processing method is relatively large, the DOM operation is complex, and such events are continuously triggered, it will cause performance losses and reduce the user experience ( UI response is slow, browser freezes, etc.). So generally speaking, we will add delayed execution logic to the corresponding event.
Usually we use the following code to implement this function:
var COUNT = 0; function testFn() { console.log(COUNT++); } // 浏览器resize的时候 // 1. 清除之前的计时器 // 2. 添加一个计时器让真正的函数testFn延后100毫秒触发 window.onresize = function () { var timer = null; clearTimeout(timer); timer = setTimeout(function() { testFn(); }, 100); };
Careful students will find that the above code is actually wrong. This is a problem that novices will make: setTimeout function The return value should be stored in a relative global variable, otherwise a new timer will be generated every time it is resized, which will not achieve the effect we sent
So we modified the code:
var timer = null; window.onresize = function () { clearTimeout(timer); timer = setTimeout(function() { testFn(); }, 100); };
The code is now normal, but there is a new problem - a global variable timer is generated. This is what we don't want to see. If this page has other functions also called timer, different codes will conflict before. In order to solve this problem, we need to use a language feature of JavaScript: closure closure. Readers with relevant knowledge can go to MDN to learn about it. The modified code is as follows:
/** * 函数节流方法 * @param Function fn 延时调用函数 * @param Number delay 延迟多长时间 * @return Function 延迟执行的方法 */ var throttle = function (fn, delay) { var timer = null; return function () { clearTimeout(timer); timer = setTimeout(function() { fn(); }, delay); } }; window.onresize = throttle(testFn, 200, 1000);
We use a closure function (throttle throttling) to put the timer internally and return the delay processing function, so that the timer variable is exposed to the outside world. It is invisible, but the timer variable can also be accessed when the internal delay function is triggered.
Of course, this way of writing is difficult to understand for novices. We can change it to another way of writing to understand it:
var throttle = function (fn, delay) { var timer = null; return function () { clearTimeout(timer); timer = setTimeout(function() { fn(); }, delay); } }; var f = throttle(testFn, 200); window.onresize = function () { f(); };
Here are the main points to understand: Throttle After being called The returned function is the real function that needs to be called when onresize is triggered
Now it seems that this method is close to perfect, but in actual use it is not the case. For example:
If the user continuously resizes the browser window size, then the delay processing function will not be executed even once
So we Another function needs to be added: when the user triggers resize, it should trigger at least once within a certain period of time . Since it is within a certain period of time, then this judgment condition can take the current time milliseconds, each time This function call subtracts the current time from the last call time, and then determines that if the difference is greater than a certain period of time, it will be triggered directly. Otherwise, the delay logic of timeout will still be used.
What needs to be pointed out in the following code is:
The role of the previous variable is similar to that of timer. They both record the last identification and must be a relative global variable
If the logic flow follows the logic of "trigger at least once", then the function call needs to be reset to the current time, which simply means: relative to the next time In fact, this is the current
/** * 函数节流方法 * @param Function fn 延时调用函数 * @param Number delay 延迟多长时间 * @param Number atleast 至少多长时间触发一次 * @return Function 延迟执行的方法 */ var throttle = function (fn, delay, atleast) { var timer = null; var previous = null; return function () { var now = +new Date(); if ( !previous ) previous = now; if ( now - previous > atleast ) { fn(); // 重置上一次开始时间为本次结束时间 previous = now; } else { clearTimeout(timer); timer = setTimeout(function() { fn(); }, delay); } } };
practice:
We simulate a throttling scenario when a window scrolls, that is to say, when the user scrolls down the page, we need to throttle the execution. Some methods, such as: calculating DOM position and other actions that require continuous manipulation of DOM elements
The complete code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>throttle</title> </head> <body> <p style="height:5000px"> <p id="demo" style="position:fixed;"></p> </p> <script> var COUNT = 0, demo = document.getElementById('demo'); function testFn() {demo.innerHTML += 'testFN 被调用了 ' + ++COUNT + '次<br>';} var throttle = function (fn, delay, atleast) { var timer = null; var previous = null; return function () { var now = +new Date(); if ( !previous ) previous = now; if ( atleast && now - previous > atleast ) { fn(); // 重置上一次开始时间为本次结束时间 previous = now; clearTimeout(timer); } else { clearTimeout(timer); timer = setTimeout(function() { fn(); previous = null; }, delay); } } }; window.onscroll = throttle(testFn, 200); // window.onscroll = throttle(testFn, 500, 1000); </script> </body> </html>
We use two cases to test the effect, which are to add at least trigger atleast parameters and Without adding:
// case 1 window.onscroll = throttle(testFn, 200); // case 2 window.onscroll = throttle(testFn, 200, 500);
case 1 behaves as follows: testFN will not be called during the page scrolling process (cannot be stopped), and will be called once when it stops, that is to say, it will be executed The last in throttle is a setTimeout, the effect is as shown in the figure (view the original gif picture):
##case 2 behaves as : During the process of page scrolling (cannot be stopped), testFN will be executed with a delay of 500ms for the first time (from at least delay logic), and then executed at least every 500ms. The effect is as shown in the figure
- Test code http://jsbin.com/tanuxegija/edit
- Full version code http:/ /jsbin.com/jigozuvuko
- Debounce VS throttle https://github.com/dcorb/debounce-throttle
The above is the detailed explanation of the JavaScript throttling function Throttle. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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.


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

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

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.