Difference and implementation of JavaScript anti-shake and throttling

Difference and implementation of JavaScript anti-shake and throttling

Preface:

As a front-end developer, there are two requirements:

(1) Search requirements

The search logic is to monitor user input events, send data to the backend after the user input is completed, the backend returns the matching data, and the frontend displays the data on the page. If a request is sent as soon as the user inputs, this will cause request pressure on the backend, and the frequency of requests needs to be controlled.

(2) The page loads data infinitely

The logic of infinitely loading data on a page is to monitor the user's scrolling events, and request the next page of data to display on the page during the user's scrolling. , then as long as you scroll, you will send a request, which will also cause pressure on the backend request, and you need to control the frequency of requests.

The above two seem to be problems of controlling request frequency, but the requirements are slightly different: search is when the user enters multiple times in the input, and the request is sent only after the user stops entering for a short time. At this time, anti-shake is needed to achieve it. Scrolling data loading means requesting data at certain intervals while the user is scrolling the page. Even if the user keeps scrolling, the request will be made instead of waiting for the user to stop scrolling. In this case, throttling is needed to achieve this.

1. Anti-shake

meaning:

A simple way to understand it is: if a user triggers an event multiple times, the event will not be executed while the user keeps triggering the event. The event will only be executed once after the user stops triggering the event for a period of time.

accomplish:

// @fn is the corresponding request data // @ms is the time interval between multiple triggers of the event by the user in milliseconds function debounce(fn, ms) {
        let timeout = null
        return function() {
            clearTimeout(timeout)
            timeout = setTimeout(() => {
                fn.apply(this, arguments)
            }, ms)
        }
    }

principle:

Each time the user triggers an event, the execution will be delayed. Before setting the delay timer, the previous delay timer will be cleared. Finally, the event will be triggered only when the interval between consecutive user triggers exceeds the parameter ms milliseconds we set.

test:

<input id="searchInput"/>
    function getData(){
        console.log('Sending request...')
    }
    document.getElementById('searchInput').oninput = debounce(getData, 800)
    // If the user keeps typing, no request will be sent // Data will only be requested once the user's continuous input interval exceeds 800ms, that is, data will be requested only if the user does not input within 800ms

2. Throttling

meaning:

A simple way to understand it is: the user triggers the event multiple times, and the event will be executed once at a certain interval while the user keeps triggering the event, and will be executed multiple times.

accomplish:

    // @fn is the corresponding request data // @ms is the time interval between multiple events triggered by the user in milliseconds function throttle(fn, ms){
        let flag = true
        return function(){
            if(!flag) return
            flag = false
            setTimeout(()=>{
                fn.apply(this, arguments)
                flag = true
            }, ms)
        }
    }

principle:

Each time a user triggers an event, a delay timer will be set. However, if a delay timer has been set, the next timer will not be started until the previous delay timer is executed. In this way, the user keeps triggering events, and the event will be executed once every certain period of time.

test:

function getData(){
        console.log('Sending request...')
    }
    window.onscroll = throttle(getData, 800)
    // While the user is scrolling, he will request data at intervals

3. Summary

Throttling and anti-shake are essentially about controlling the frequency of event execution, but the timing of triggering events is essentially different. Anti-shake is when a user triggers an event multiple times, and when the user stops triggering the event, the event is executed once; throttling is when a user triggers an event multiple times, and the event is executed at intervals during the multiple triggering processes.

This concludes this article about the difference and implementation of JavaScript anti-shake and throttling. For more information about the difference and implementation of anti-shake and throttling, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Throttling and debounce of javascript functions
  • Detailed explanation of javascript debounce function
  • Javascript throttle function and debounce function
  • What is JavaScript anti-shake and throttling
  • Let's talk in detail about what js anti-shake throttling is
  • JavaScript debounce and throttling

<<:  Five practical tips for web form design

>>:  Summary of 7 reasons why Docker is not suitable for deploying databases

Recommend

Several ways to shut down Hyper-V service under Windows 10

When using VMware Workstation to open a virtual m...

MySQL 8.x msi version installation tutorial with pictures and text

1. Download MySQL Official website download addre...

HTML Tutorial: DOCTYPE Abbreviation

When writing HTML code, the first line should be ...

Vue implements the question answering function

1. Request answer interface 2. Determine whether ...

Docker container time zone adjustment operation

How to check if the Docker container time zone is...

Windows Server 2016 Quick Start Guide to Deploy Remote Desktop Services

Now 2016 server supports multi-site https service...

WeChat applet implements the Record function

This article shares the specific code for the WeC...

Native JavaScript to achieve the effect of carousel

This article shares the specific code for JavaScr...

PHP-HTMLhtml important knowledge points notes (must read)

1. Use frameset, frame and iframe to realize mult...

A detailed introduction to JavaScript execution mechanism

Table of contents 1. The concept of process and t...

vue3+ts+EsLint+Prettier standard code implementation

Table of contents use Use of EsLint Add a profile...

About MySQL innodb_autoinc_lock_mode

The innodb_autoinc_lock_mode parameter controls t...