search
HomeWeb Front-endJS TutorialDetailed explanation of throttling and anti-shaking of javascript functions

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 continuous 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 = $(&#39;.scroll-box&#39;);
  //调用throttle函数,传入相应的方法和规定的时间;
  var thro = throttle(throFun,300);
  //触发事件;
  scrollBox.on(&#39;scroll&#39; , 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(&#39;success&#39;);
  }
 })
</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 continues to execute, the method in the timer will continue to be cleared. The function will not be executed until our operation is completed;

In fact There are many ways to write, and the main problem is the idea. If you write 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 resizing the window, we can use anti-shake technology or throttling;
  1. mousemove mouse movement event, we can use either anti-shake or throttling Use throttling;
  2. Scroll events triggered by the scroll bar can of course use either anti-shake or throttling;
  3. Continuous high-frequency events Events can be resolved in these two ways to optimize page performance;
  4. Which one is more appropriate mainly depends on your business needs.
  5. Related recommendations:

The meaning of function throttling and anti-shake

Detailed analysis of JS function debouncing and throttling_Basic knowledge

Detailed explanation of JavaScript function throttling and detailed explanation of method examples

The above is the detailed content of Detailed explanation of throttling and anti-shaking of javascript functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 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.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 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.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 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.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 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.

See all articles

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

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools