JavaScript anti shake & throttling

Keywords: Javascript ECMAScript html Ajax

Anti chattering and throttling are events that prevent high frequency triggering

Anti shake, generally used in

Onresize event (onresize: execute Javascript code when the browser is resized)

oninput event: triggered upon user input.

If the event is triggered with high frequency, it is likely to cause the server to crash

Then you can use the function anti shake for optimization. For example, when you take the elevator, the mechanism of the elevator is that when people enter the elevator, they will automatically close the door within ten seconds, and people can enter and exit within ten seconds. When ten seconds, no matter whether anyone enters or goes out, they will directly close the door and operate on time.

The throttling is different. The elevator operates in ten seconds. If someone enters or goes out within ten seconds, the timing will restart in ten seconds, and the door will not close until no one flows within ten seconds

Simple understanding of function throttling

Execute at regular intervals

Simple understanding of function anti chattering

Every time an event is triggered, the timer will be reset until the last event is triggered and then executed

Anti shake is generally used to trigger input events

For example:

<body>
    Please enter information:<input type="text">
    <script>
        var input =document.querySelector('input');
        input.oninput = function(){
            console.log('Event triggered');
        }
    </script>
</body>

The effects are as follows:

When we input text, we will send a request every time. In this way, many things in the middle do not need to be sent to the back end. If they are given, it will put great pressure on the server. Here, we can use function anti shake for optimization  

After optimization:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Anti shake optimization</title>
</head>
<body>
    Please enter information:<input type="text">
    <script>
    var processor = {  
    timeoutId: null,
    performProcessing: function() {
    var days = new Date()
    var a= days.getHours();
    var b= days.getMonth();
    var c= days.getSeconds();
    var d= days.getMilliseconds();
    console.log(a+'Time'+b+'branch'+c+'second'+d+'millisecond');
    },
  	process: function() {
  	  var that = this;
      clearTimeout(that.timeoutId);    
      that .timeoutId = setTimeout(function() {
        that.performProcessing();
      }, 500)                     //Execute every 500 milliseconds. If the input is still in less than five seconds, the calculation will restart in these 500 milliseconds
  	}
  };
  document.querySelector('input').oninput = function() {
  	processor.process();
  }
    </script>
</body>
</html>

  The effect is shown in the following figure:

  throttle

Principle: specify a time during which all events will be executed together

Generally used for: resize, touchmove, move DOM, pull-up list, load data, etc

details

<body>
    <div>
        Add throttling-timer & Timestamp:<input type="text" id="throttle"/>
    </div>
    <script>
        window.onload = () => {
            function ajax (data) {
                console.log(new Date().toLocaleTimeString() + ' - ' + data)
            }
            function throttle(fn, delay) {
                let last
                return args => {        
                    let now = Date.now()

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

                        fn.id = setTimeout(() => {
                            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>

 

Posted by Bleej on Thu, 16 Sep 2021 11:07:33 -0700