The introduction of

Some calculations and processing in browsers are very expensive. For example, when the mouse responds to resize, touchmove, Scroll and other operations, the frequency of triggering of the binding function will be very high. If the function is a little more complicated, the response speed will be far behind the triggering frequency, resulting in stalling, delay, suspended animation and other phenomena.

Here’s an example of sending an Ajax request based on the data entered in the input field:


      
<html>
<head>
    <title>Ordinary processing</title>
</head>
<body>
    <div>Common treatment:<input type="text" id="index"/>
    </div>
    <script>
        window.onload = (a)= > {
            function ajax (data) {
                console.log(new Date().toLocaleTimeString() + The '-' + data)
            }

            document.querySelector('#index').addEventListener('keyup', e => {
                ajax(e.target.value)
            })
        }
    </script>
</body>
</html>
Copy the code

The general processing results are as follows:

As you can see in the figure above, it is a waste of resources to continuously send requests while typing. To optimize performance, we can use anti-shake or throttling to prevent functions from being called frequently.

Stabilization Debounce

The principle of

Execute the callback function n seconds after the event is triggered. If the event is retriggered within n seconds, the timer is reset. The result is to consolidate frequently triggered events into one and execute them last.

For example,

The elevator will close and start working in 5 seconds. If someone comes in, wait 5 seconds. If someone comes in again in 5 seconds, wait 5 seconds to reset the timer. The elevator didn’t start working until more than five seconds later.

Usage scenarios

Input Request server, etc.

implementation

Whenever an event is triggered, the timer is reset. Wait n seconds until the last event is triggered before executing the callback function.


      
<html>
<head>
    <title>Join the stabilization</title>
</head>
<body>
    <div>Add anti-shake:<input type="text" id="debounce"/>
    </div>
    <script>
        window.onload = (a)= > {
            function ajax (data) {
                console.log(new Date().toLocaleTimeString() + The '-' + data)
            }

            function debounce (fn, delay) {
                return args= > {
                    clearTimeout(fn.id)

                    fn.id = setTimeout((a)= > {
                        fn.call(this, args)
                    }, delay)
                }
            }
           
            const debounceAjax = debounce(ajax, 1000)

            document.querySelector('#debounce').addEventListener('keyup', e => {
                debounceAjax(e.target.value)
            })
        }
    </script>
</body>
</html>
Copy the code

Add the anti-shake result as follows:

Throttling Throttle

The principle of

Specify a time n, n seconds, to trigger the event into one and execute.

For example,

The elevator will operate on time 5 seconds after the first person comes in, without waiting, and will not reset if there are still people coming in within 5 seconds.

Usage scenarios

Resize, TouchMove move DOM, pull-up list load data, etc.

Timer 1.


      
<html>
<head>
    <title>Add throttle-timer</title>
</head>
<body>
    <div>Add throttle-timer:<input type="text" id="throttle"/>
    </div>
    <script>
        window.onload = (a)= > {
            function ajax (data) {
                console.log(new Date().toLocaleTimeString() + The '-' + data)
            }

            function throttle (fn, delay) {
                return args= > {
                    if (fn.id) return

                    fn.id = setTimeout((a)= > {
                        fn.call(this, args)
                        clearTimeout(fn.id)
                        fn.id = null
                    }, delay)
                }
            }

            const throttleAjax = throttle(ajax, 1000)

            document.querySelector('#throttle').addEventListener('keyup', e => {
                throttleAjax(e.target.value)
            })
        }
    </script>
</body>
</html>
Copy the code

Adding throttle-timer results are as follows:

2. The timestamp


      
<html>
<head>
    <title>Add throttle-timestamp</title>
</head>
<body>
    <div>Add throttle-timestamp:<input type="text" id="throttle"/>
    </div>
    <script>
        window.onload = (a)= > {
            function ajax (data) {
                console.log(new Date().toLocaleTimeString() + The '-' + data)
            }

            function throttle (fn, delay) {
                let last = 0

                return args= > {        
                    let now = Date.now()

                    if (now > last + delay) {
                        fn.call(fn, args)
                        last = now
                    }
                }
            }

            const throttleAjax = throttle(ajax, 1000)

            document.querySelector('#throttle').addEventListener('keyup', e => {
                throttleAjax(e.target.value)
            })
        }
    </script>
</body>
</html>
Copy the code

Adding throttle-timestamp results are as follows:

Timers & timestamps


      
<html>
<head>
    <title>Add throttle-timer & timestamp</title>
</head>
<body>
    <div>Add throttle-timer & timestamp:<input type="text" id="throttle"/>
    </div>
    <script>
        window.onload = (a)= > {
            function ajax (data) {
                console.log(new Date().toLocaleTimeString() + The '-' + data)
            }

            function throttle(fn, delay) {
                let last

                return args= > {        
                    let now = Date.now()

                    if (last && now < last + delay) {      
                        clearTimeout(fn.id)

                        fn.id = setTimeout((a)= > {
                            fn.call(this, args)
                            last = now
                        }, delay)
                    } else {
                        fn.call(this, args)
                        last = now
                    }
                }
            }

            const throttleAjax = throttle(ajax, 1000)

            document.querySelector('#throttle').addEventListener('keyup', e => {
                throttleAjax(e.target.value)
            })
        }
    </script>
</body>
</html>
Copy the code

Add throttle-timer & timestamp as follows:

summary

This paper mainly introduces the realization of anti – shake and throttling. Among them, the core idea of anti-shake is to execute the high-frequency operation only once after N seconds; Throttling is performed every once in a while.

Thanks for reading and please point out any questions.