search
HomeWeb Front-endJS TutorialDetailed 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 = $(&#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 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;
  1. mousemove mouse movement event, we can use either anti-shake technology 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. Related recommendations:
  5. Detailed explanation of JS function throttling and anti-shake examples


Detailed explanation of throttling and anti-shaking of javascript functions

The meaning of function throttling and anti-shaking

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!

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: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 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.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

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: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

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.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!