


Detailed explanation of throttling and anti-shake debounce of javascript function
This article mainly introduces the throttling [throttle] and anti-shake [debounce] of JavaScript functions. It introduces the principles and examples of throttling and anti-shake in detail. It has certain reference value. Those who are interested can learn more. I hope Can help everyone.
Anti-shake and throttling
When resize, scroll, input box content verification and other operations of the window, if these operation processing functions are more complex or the page When operations such as frequent re-rendering are performed, if the frequency of event triggering is unlimited, it will increase the burden on the browser and lead to a very poor user experience. At this time, we can use debounce (anti-shake) and throttle (throttle) to reduce the frequency of triggering without affecting the actual effect.
These two things appear for project optimization. There is no official definition. Their appearance is mainly to solve the poor performance and memory caused by some events that are continuously executed in a short period of time. Problems such as huge consumption;
Such events, such as scroll keyup, mousemove resize, etc., are triggered continuously in a short period of time, which consumes a lot of money in terms of performance, especially operations that change the DOM structure;
Throttle [throttle] is very similar to anti-shake [debounce]. They both allow the above-mentioned events to be triggered how many times within a specified period of time when the specified event changes from constant triggering to a specified time;
Throttle [throttle]
The popular explanation of throttling is like when we put water into the faucet, when the valve is opened, the water flows down. This upholds the fine traditional virtues of diligence and thrift. , we need to turn down the faucet, it is best to let it drip down drop by drop within a certain time interval according to a certain rule according to our will. This,,, well this is our concept of throttling;
In terms of a function, use the setTimeout method, given two times, subtract the previous time from the later time, and trigger the event once when the time we give is reached. This is too general. Let's look at the following function , here we take [scroll] as an example;
/** 样式我就顺便写了 **/ <style> *{padding:0;margin:0;} .scroll-box{ width : 100%; height : 500px; background:blue; overflow : auto; } .scroll-item{ height:1000px; width:100%; } </style>
------------------------
/** 先给定DOM结构;**/ <p class="scroll-box"> <p class="scroll-item"></p> </p>
---------------------
/**主要看js,为了简单我用JQ去写了**/ <script> $(document).ready(function(){ var scrollBox = $('.scroll-box'); //调用throttle函数,传入相应的方法和规定的时间; var thro = throttle(throFun,300); //触发事件; scrollBox.on('scroll' , function(){ //调用执行函数; thro(); }) // 封装函数; function throttle(method,time){ var timer = null; var startTime = new Date(); return function(){ var context = this; var endTime = new Date(); var resTime = endTime - startTime; //判断大于等于我们给的时间采取执行函数; if(resTime >= time){ method.call(context); //执行完函数之后重置初始时间,等于最后一次触发的时间 startTime = endTime; } } } function throFun(){ console.log('success'); } }) </script>
Through the above function, we can achieve the throttling effect and trigger it every 300 milliseconds. Of course, the time can be customized according to needs;
Prevention Debounce [debounce]
Before writing the code, let’s first clarify the concept of anti-shake. I wonder if you have ever done something like floating advertising windows on both sides of the computer. When we drag the scroll bar Sometimes, the advertising windows on both sides will constantly try to be in the middle due to the dragging of the scroll bars, and then you will see these two windows shaking and shaking;
Generally this This is called jitter. What we have to do is to prevent this kind of jitter, which is called debounce;
The idea of debounce here is that after we finish dragging, the positions of the windows on both sides will be reset. Calculation, in this way, will appear very smooth and comfortable to look at, and the number of times of operating the DOM structure, the most important thing, will be greatly reduced;
optimizes page performance and reduces memory consumption, otherwise you will be like IE If you use an older version of the browser, it might just pop up for you
In written terms, the function will not be executed until a certain event ends. When it ends, we give Delay time, then he will execute this function after the given delay time. This is the anti-shake function;
Look at the code:
//将上面的throttle函数替换为debounce函数; function debounce(method,time){ var timer = null ; return function(){ var context = this; //在函数执行的时候先清除timer定时器; clearTimeout(timer); timer = setTimeout(function(){ method.call(context); },time); } }
The idea is that before the function is executed, we clear the timer first. If the function keeps executing, it will continue to clear the methods in the timer. The function will not be executed until our operation is completed;
In fact There are many ways to write, and it is mainly a question of ideas. The more you write, the more you will naturally understand; When we press the keyboard, we can use the anti-shake function. Otherwise, we will request it every time we press the keyboard. The request is too frequent. In this way, we will request again when we finish pressing the keyboard. The request will be much less, and the performance will naturally go without saying;
- resize When adjusting the window size, we can use anti-shake technology or throttling;
- mousemove mouse movement event, we can use either anti-shake technology or throttling Use throttling;
- Scroll events triggered by the scroll bar can of course use either anti-shake or throttling;
- Continuous high-frequency events Events can be resolved in these two ways to optimize page performance;
- Related recommendations:
- Detailed explanation of JS function throttling and anti-shake examples
The above is the detailed content of Detailed explanation of throttling and anti-shake debounce of javascript function. For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
