In order to deepen their understanding of anti-shake + throttling, implement two simple cases to deepen their impression.

Function throttle

Further understanding of function throttling by implementing a small example of dragging and dropping Dom elements

  • Situation: whendragThe drag event is executed and the DragFn function is called multiple times within 1 second.
  • Effect: If the function is executed multiple times in 1 second, the function can only be executed once in 1 second (5 times in 5s).

  • Drag.js – Sample code
"use strict";

// Function throttle - Scenario: call the DragFn function multiple times in 1 second when the drag drag event is executed.
If the DragFn function is executed multiple times in 1 second, then the DragFn function can only be executed once in 1 second (5 times in 5s).
(function(){
  const box_dom  = document.getElementsByClassName('box') [0];
  let isDrag = false; // Drag state
  let drag_position = {}; // Record the element coordinates when the drag begins
  
  // Start dragging
  // clientX/clientY - Horizontal/vertical coordinates of the mouse pointer
  box_dom.addEventListener('dragstart'.function(e){
    if(e.target === box_dom){
      isDrag = true;
      The getBoundingClientRect method returns the size of the element and its position relative to the viewport
      let{left,top} = box_dom.getBoundingClientRect(); drag_position.left = e.clientX - left; drag_position.top = e.clientY - top; }},false)
  
  const DragFn = throttle(Fn,1000);
  // Drag and drop to move
  box_dom.addEventListener('drag',DragFn,false);
  // End of drag
  box_dom.addEventListener('dragend'.function(e){
    isDrag = false;
  },false)
  
  function throttle(fn,timer){
    let init_time = 0;
    // The callback function is provided to the drag event
    return function(. args){
      let now_time = +new Date(a);if(now_time-init_time > timer){
        init_time = now_time;
        fn.apply(this,args); }}}// The function executed by the throttling
  function Fn(e){
    e.preventDefault();
    if(isDrag&&e.clientX! = =0) {let t_left = e.clientX - drag_position.left;
      let t_top = e.clientY - drag_position.top;
      box_dom.style.left = t_left+'px';
      box_dom.style.top = t_top+'px';

      const timer = new Date(a);console.log(`${timer.getMinutes()}:${timer.getSeconds()} ---------- Drag Dom----------`); }}}) ()Copy the code

2, function anti-shock (debounce)

Input If the input continues within 2 seconds, the timer goes back to 2 seconds and the function does not execute (back to the table). The function is executed after 2 seconds of input.

  • Function: For example, by listeninginput keydownIn order to avoid executing requests too frequently, you need to optimize using function stabilization.

  • Search.js – Sample code
"use strict";
// function debounce - Scenario: when input input, like a background request to search for content.
// If the input is reentered within 2 seconds, the timer goes back to 2 seconds and the function is not executed (back to table).

(function(){
  const SeachDom = document.getElementsByTagName('input') [0];

  const KeyDownFn = debounce(Fn,2000);
  SeachDom.addEventListener('keydown',KeyDownFn);

  function debounce(fn,timer){
    let timer_out = null;

    return function(. args){
      // Clear the timer
      if(timer_out) clearTimeout(timer_out);

      timer_out = setTimeout((a)= >{
        fn.apply(this,args);
      },timer)

    }
  }

  // Request a search content operation
  function Fn(e){
    console.log(e.target.value, '<------search values');
  }

})();

Copy the code

HTML code


      
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Function anti-shake/throttling Demo</title>
  <style>
    html.body{
      width: 100%;
      height: 100%;
      padding:0;
      margin:0;
    }
    .box..debounce{
      width: 200px;
      height: 200px;
      background: skyblue;
      position: absolute;
      left: 20px;
      top: 20px;
      border-radius: 10px;
    }
    .debounce{
      top: 300px;
      background: yellowgreen;
      line-height: 200px;
      text-align: center;
      padding: 0 20px;
    }
    
    .debounce input{
      top: 300px;
      display: inline-block;
      height: 30px;
      width: 100%;
      font-size: 16px;
      padding-left: 10px;
    }
    .box{
      cursor: move;

    }
    .box>p..debounce>p{
      margin: 0;
      display: flex;
      height: 100%;

      line-height: 30px;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: # 333;
    }
  </style>
</head>
<body>
  <section class="box" draggable="true">
    <p>
      <span>Drag and drop the throttle</span>
      <span>(Move once every 1 second)</span>
    </p>
    

  </section>
  <section class="debounce">
    <p>
      <input type="text" placeholder="Search anti-shake" class="search-input">
      <br/>
      <span>Enter 2 seconds after completion</span>
      <span>Executing a search request</span>
    </p>
  </section>

  <! - drag - >
  <script src='./src/drag.js'></script>
  <! - search - >
  <script src='./src/search.js'></script>
</body>
</html>
Copy the code