preface

This article explains the idea of JS stabilization, below the basic code to achieve stabilization, you can copy to your editor to see the effect oh. There are practical application scenarios, such as HTML, CSS, JQuery, and sending Ajax requests using JQuery.


First, what is shaking?

Shaking prevents the event from being called multiple times and only executes once in a given time.

2. What problems has shaking stabilization solved

Let’s say a user clicks a button very frequently. After clicking the button, it sends a request to the background. If you don’t use stabilization, it sends a lot of repetitive Ajax requests and strains the server. With shaking, Ajax requests are sent only once in a specified period of time, effectively relieving the strain on the server.

Three, the realization of the basic code

By listening for input events in the input box and using the timer to obtain the content entered by the user every second. If the user enters again within one second, the last timer is cleared and the content entered by the user is printed to the console after the end of the timer.

<! DOCTYPEhtml>
<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>debounce</title>
  </head>
  <body>
      <input type="text" placeholder="Please enter what you are searching for ~" />
    <script>
      let timer = null
      $('input').on('input'.function(){
          console.log('No tremors', $('input').val())
          // To clear a timer
          clearTimeout(timer)
          // Restart a timer
          timer = setTimeout(() = > {
              // If the value of the input box is null, the following code is terminated
              if(! $('input').val()) return
              console.log('With the addition of anti-shaking.', $(this).val())
          }, 1000);
      })

      // $('input').on(
      // 'input',
      // debounce(function () {
      // if (! $(this).val()) return
      // console.log($(this).val())
      / /})
      // )
      // // encapsulates code and improves code reusability
      // function debounce(fn) {
      // let timer = null
      // return function () {
      // clearTimeout(timer)
      // timer = setTimeout(() => {
      // //, where this points to window
      // // changes the point to this through the call() method
      // fn.call(this)
      / /}, 1000)
      / /}
      // }
    </script>
  </body>
</html>

Copy the code

Iv. Application scenarios of anti-shaking

Presumably, we all have the habit of shopping websites. When we search for an item in the search box, as long as we input the keyword, the corresponding associative list will appear under the search box. However, the Lenovo list is not displayed in real time, which can be delayed for 500 milliseconds or 1 second. The keywords entered by the user can be submitted to the background through Ajax request. When the response from the background server is received, the Lenovo list will be displayed to the user. This operation greatly reduces the request pressure on the server, delays the appropriate time, and allows the user to have enough time to complete the search keyword.

1. Code implementation

The code is as follows (example) :

<! DOCTYPEhtml>
<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>Image stabilization</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      div {
        width: 500px;
        margin: auto;
      }
      .box {
        margin-top: 200px;
        width: 500px;
        height: 35px;
        border: 1px solid #ccc;
        border-radius: 8px;
        overflow: hidden;
      }

      a {
        text-decoration: none;
        color: #fff;
        width: 60px;
        height: 100%;
        line-height: 35px;
        text-align: center;
        background-color: steelblue;
      }

      .fl {
        float: left;
      }

      .fr {
        float: right;
      }

      input {
        padding-left: 20px;
        width: 418px;
        height: 100%;
        border: 0;
        outline: none;
      }

      .list {
        display: none;
        width: 500px;
        border: 1px solid #ccc;
        border-top: none;
        border-radius: 8px;
      }

      li {
        list-style: none;
        padding-left: 30px;
        height: 30px;
        line-height: 30px;
        border-bottom: 1px solid #ccc;
      }

      li:last-child {
        border-bottom: none;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <input type="text" class="fl" placeholder="Please enter what you are searching for ~" />
      <a href="javascript:;" class="fr">search</a>
    </div>
    <div class="list">
      <ul></ul>
    </div>

    <script src=". / jquery - 3.5.1 track of. Min. Js. ""></script>
    <script>
      let timer = null
      // Bind the input event to the input box
      $('input').on('input'.function () {
        clearTimeout(timer)
        timer = setTimeout(() = > {
          // If the input field is empty, the execution of the code is terminated
          if(! $(this).val()) return
          
          let kw = $(this).val()
          
          // Send the Ajax request
          $.ajax({
            type: 'GET'.url: 'http://www.liulongbin.top:8000/v1_0/suggestion?q=' + kw,
            success: function (res) {
              // Determine the result returned by the server, and terminate subsequent code execution if there is no content pop-up
              if (res.data.options.length === 0) {
                alert('No search results yet ~'The $()'input').val(' ')
                return
              }
              // Iterate over the data returned by the server
              res.data.options.forEach(item= > {
                // Append each item to the ul list
                $('.list ul').append(`<li>${item}</li>`)})// Display the associative list
              $('.list').show()
            }
          })
        }, 1000)
        // Hide the association list display and empty the contents of ul
        $('.list').hide().find('ul').empty()
      })
    </script>
  </body>
</html>

Copy the code

2. Result presentation


conclusion

Originally wanted to give you a GIF to show, but did not find the software, interested partners can copy the code to their own editor to run to see the effect. If you think it will help you, please click “like” to support ~ 3 grams of oil