


Application of JavaScript anti-shake and throttling and introduction to implementation methods (code examples)
The content of this article is about the application of JavaScript anti-shake and throttling and the introduction of implementation methods (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. help.
First give an example:
Simulates making an ajax query request after inputting in the input box, without adding anti-shake and throttling effects. Here is the complete executable code:
nbsp;html> <meta> <title>没有防抖</title> <style></style> <script> window.onload = function () { //模拟ajax请求 function ajax(content) { console.log('ajax request ' + content) } let inputNormal = document.getElementById('normal'); inputNormal.addEventListener('keyup', function (e) { ajax(e.target.value) }) } </script> <div> 1.没有防抖的输入: <input> </div>
Effect: Entering one in the input box will trigger an "ajax request" (here is the console).
No anti-shake and throttling
Disadvantages: Waste of request resources, you can add anti-shake and throttling to optimize it.
This article will introduce what anti-shake and throttling are, their application scenarios, and implementation methods. Anti-shake and throttling are both intended to solve performance problems caused by triggering a large number of functions in a short period of time. For example, if the trigger frequency is too high, the response speed cannot keep up with the trigger frequency. Delay, freeze or freeze. However, the business needs they deal with are different, so the implementation principles are also different. Let’s take a look at them in detail below.
1. Debounce
1.1 What is debounceExecute the callback function n seconds after the event is triggered. If If it is triggered again within these n seconds, the time will be restarted. 1.2 Application Scenario(1) After the user continuously inputs a string of characters in the input box, the last query ajax request will only be executed after the input is completed, which can effectively reduce the number of requests. times, saving request resources; (2) The resize and scroll events of the window will trigger the corresponding events when constantly adjusting the browser window size or scrolling, and the anti-shake will only trigger it once;1.3 Implementation is still the same as above. Here, anti-shake is added to optimize it. The complete code is as follows:
nbsp;html> <meta> <title>加入防抖</title> <style></style> <script> window.onload = function () { //模拟ajax请求 function ajax(content) { console.log('ajax request ' + content) } function debounce(fun, delay) { return function (args) { //获取函数的作用域和变量 let that = this let _args = args //每次事件被触发,都会清除当前的timeer,然后重写设置超时调用 clearTimeout(fun.id) fun.id = setTimeout(function () { fun.call(that, _args) }, delay) } } let inputDebounce = document.getElementById('debounce') let debounceAjax = debounce(ajax, 500) inputDebounce.addEventListener('keyup', function (e) { debounceAjax(e.target.value) }) } </script> <div> 2.加入防抖后的输入: <input> </div>
2.Throttle
2.1 What is throttling Specifies a unit time. Within this unit time, the callback function that triggers the event can only be executed once. If an event is triggered multiple times in the same unit time, only one time can take effect. 2.2 Application Scenario(1) The mouse continuously triggers an event (such as click), and only triggers it once per unit time; (2) On the page In the infinite loading scenario, the user needs to send an ajax request every once in a while while scrolling the page, instead of requesting data only when the user stops scrolling the page; (3) Monitor the scrolling event, For example, whether to slide to the bottom to automatically load more, use throttle to judge; 2.3 Implementation It is still the above example, add throttling here to optimize it, the complete code is as follows:nbsp;html> <meta> <title>加入节流</title> <style></style> <script> window.onload = function () { //模拟ajax请求 function ajax(content) { console.log('ajax request ' + content) } function throttle(fun, delay) { let last, deferTimer return function (args) { let that = this; let _args = arguments; let now = +new Date(); if (last && now < last + delay) { clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fun.apply(that, _args); }, delay) } else { last = now; fun.apply(that, _args); } } } let throttleAjax = throttle(ajax, 1000) let inputThrottle = document.getElementById('throttle') inputThrottle.addEventListener('keyup', function (e) { throttleAjax(e.target.value) }) } </script> <div> 3.加入节流后的输入: <input> </div>
3. Summary
Summarize the difference between anti-shake and throttling: -- Effect: Function anti-shake is within a certain period of time It is only executed once; function throttling is executed at intervals. No matter how frequently the event is triggered, it is guaranteed that the real event processing function will be executed once within the specified time. -- Principle: Anti-shake maintains a timer, which stipulates that the function is triggered after the delay time. However, if it is triggered again within the delay time, the current timer will be cleared and the timeout will be reset. Called, that is, retiming. In this way, only the last operation can be triggered. Throttling is a function that is triggered by judging whether a certain time is reached. If the specified time is not reached, a timer is used to delay, and the next event will reset the timer.The above is the detailed content of Application of JavaScript anti-shake and throttling and introduction to implementation methods (code examples). 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











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

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

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

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

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

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Django: A magical framework that can handle both front-end and back-end development! Django is an efficient and scalable web application framework. It is able to support multiple web development models, including MVC and MTV, and can easily develop high-quality web applications. Django not only supports back-end development, but can also quickly build front-end interfaces and achieve flexible view display through template language. Django combines front-end development and back-end development into a seamless integration, so developers don’t have to specialize in learning

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.
