search
HomeWeb Front-endJS TutorialTalk about function throttling in JS

The purpose of function throttling

It can be understood literally. Function throttling is used to throttle functions and optimize performance to a certain extent. For example, DOM operations are more efficient than non-DOM operations Interaction requires more memory and CPU time. Attempting to perform too many DOM-related operations in succession can cause the browser to hang and sometimes even crash. Especially using onresize in IE It is easy to happen when the event handler is used. When the browser is resized, the event will be triggered continuously. Inside the onresize event handler if you try to access the DOM operation, its high frequency of changes may crash the browser. For another example, for a common search function, we usually bind the keyup event and search every time the keyboard is pressed. But our purpose is mainly to search every time we enter some content. In order to solve these problems, you can use timers to throttle functions.

The principle of function throttling

Some codes cannot be executed continuously and repeatedly without interruption. The first time the function is called, a timer is created to run code after a specified interval. When the function is called a second time, it clears the previous timer and sets another one. If the previous timer has already been executed, this operation has no meaning. However, if the previous timer has not yet been executed, it is actually replaced with a new timer. The purpose is to execute the function only after the request to execute it has been stopped for some time.

Basic mode of function throttling

var processor = {
   timeoutId: null,
     //实际进行处理的方法
   performProcessing: function(){
     //实际执行的代码
   },
  //初始处理调用的方法
  process: function(){
    clearTimeout(this.timeoutId);
    var that = this;
    this.timeoutId = setTimeout(function(){
      that.performProcessing();
    }, 100);
  }
};
//尝试开始执行
processor.process();
Okay, I’m definitely a little confused. Let’s use an example to explain in detail, and do an optimization based on this basic model.

Example scenario: Implementing common search functions

① Without using function throttling, bind the keyup event processing function to the input and output the content I input on the console.

Test main code:

<input id="search" type="text" name="search">
rrree

The result is as shown in the figure:

Talk about function throttling in JS


It can be seen that in this case, every time a keyboard key is pressed, it is output once. A short piece of content was output 14 times. If each time was an ajax query request, 14 requests would have been sent. The consumption in performance can be imagined.

②The case of using basic function throttling mode.

Test main code:

   
function queryData(text){
    console.log("搜索:" + text);
  }
var input = document.getElementById("search");
  input.addEventListener("keyup", function(event){ queryData(this.value);
});
rrree

The results are as shown in the figure:

It can be seen that in this case, a lot of content was input and only output once, because the interval between two inputs was set to 500ms during the test. The actual application can be set according to the situation. Obviously, this has been greatly optimized in terms of performance. However, in this case, there is a new problem, as shown below:

Talk about function throttling in JS


Okay, maybe there is no clue. In fact, the problem is that if I keep typing and input a lot of content, but the interval between each two inputs is less than the delay value I set, then the queryData search function will never be called. In fact, what we prefer is that when a certain time value is reached, this search function must be executed once. Therefore, there is an improved model of function throttling.

③Function throttling enhanced version

Main code tested:

<input id="search" type="text" name="search">


function queryData(text){
  console.log("搜索:" + text);
}
var input = document.getElementById("search");
input.addEventListener("keyup", function(event){
  throttle(queryData, null, 500, this.value);
  // queryData(this.value);
});
function throttle(fn,context,delay,text){
  clearTimeout(fn.timeoutId);
  fn.timeoutId = setTimeout(function(){
  fn.call(context,text);
  },delay);
}


The test results are as shown in the figure:

Talk about function throttling in JS


Obviously, after continuous input, after a certain time interval, the queryData function will inevitably be called, but it is not called frequently. This achieves the purpose of saving money without affecting the user experience.

④Further optimization

If you go further, you can judge the input content before calling the throttle function. If the value is empty or the value remains unchanged, there is no need to call it again. I won’t go into details here.

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: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),