search
HomeWeb Front-endJS TutorialApplication 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(&#39;ajax request &#39; + content)
            }
            let inputNormal = document.getElementById(&#39;normal&#39;);

            inputNormal.addEventListener(&#39;keyup&#39;, 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).

Application of JavaScript anti-shake and throttling and introduction to implementation methods (code examples)

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 debounce

Execute 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(&#39;ajax request &#39; + 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(&#39;debounce&#39;)
            let debounceAjax = debounce(ajax, 500)
            inputDebounce.addEventListener(&#39;keyup&#39;, function (e) {
                debounceAjax(e.target.value)
            })
        }
    </script>



    <div>
        2.加入防抖后的输入:
        <input>
    </div>

Code description:

1. Each time an event is triggered , will clear the current timer and then reset the timeout call, that is, re-timing. This will cause each high-frequency event to cancel the previous timeout call, causing the event handler to not be triggered;

2. Only when the high-frequency event stops, the timeout call triggered by the last event can be delayed. Execute after time;

Effect:

After adding anti-shake, when you continue to input in the input box, the request will not be sent. Only when there is no further input within the specified time interval, The request will be sent. If you stop inputting first, but then input again within the specified interval, the timing will be retriggered.

Application of JavaScript anti-shake and throttling and introduction to implementation methods (code examples)

Add anti-shake

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(&#39;ajax request &#39; + 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(&#39;throttle&#39;)
            inputThrottle.addEventListener(&#39;keyup&#39;, function (e) {
                throttleAjax(e.target.value)
            })
        }
    </script>


    <div>
        3.加入节流后的输入:
        <input>
    </div>

Effect: The experiment found that when inputting continuously, the settings in the code will be installed and an ajax request will be executed every 1 second

Application of JavaScript anti-shake and throttling and introduction to implementation methods (code examples)

Add throttling

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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools