Web project development JS function anti-shake and throttling sample code

Web project development JS function anti-shake and throttling sample code

Stabilization

Classic application common: accordion effect

Introduction

Website without anti-shake:

insert image description here

Websites with anti-shake:

Please add a description of the image

Anti-shake scene 1 (mouse move in)

Jitter: The user does not intend to trigger this interaction, but the interaction event is accidentally triggered due to accidental mouse jitter.
Example: I want to see the fifth picture. I don't want to see 2 3 4 pictures. But when the mouse slid from the first picture to the fifth picture, it accidentally landed on 2 3 4. False trigger.

Function anti-shake: If a user triggers an event multiple times in a row, only the last one will be executed.

Solution principle: Turn on the timer. If the event is triggered multiple times within the interval, clear the previous timer each time.

Example and solution code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Animation-Case Study "Accordion"</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      ul {
        list-style: none;
        width: 2400px;
      }
      #box {
        width: 1200px;
        height: 400px;
        border: 1px solid red;
        margin: 100px auto;
        overflow: hidden;
      }
      #box li {
        width: 100px;
        height: 400px;
        float: left;
        transition: all 0.5s ease-out;
      }
      #box li.over {
        width: 800px;
      }
    </style>
  </head>

  <body>
    <div id="box">
      <ul>
        <li v-for="(item,index) in list" :class="{over:overIndex == index}" @mouseenter="doEnter(index)">
            <img :src="item" alt="">
        </li>
      </ul>
    </div>
    <script src="./vue.js"></script>
    <script>
      let app = new Vue({
          el:'#box',
          data:{
              overIndex:0,
              list:[
                  './images/collapse/1.jpg',
                  './images/collapse/2.jpg',
                  './images/collapse/3.jpg',
                  './images/collapse/4.jpg',
                  './images/collapse/5.jpg',
              ],
              timeID:null
          },
          methods: {
              doEnter(index){
                  /* Enable anti-shake*/
                  //1.1 Clear the last timer first, and use this time as the reference clearTimeout(this.timeID)
                  //1.2 Start the timer (anti-shake interval)
                  this.timeID = setTimeout(()=>{
                    this.overIndex = index;
                  },500)
              }
          },
      })
    </script>
  </body>
</html>

Anti-shake scene 2 (keyboard keys)

Classic application scenario: search for associated words
-Under development, the backend of this function will use the middleware "OpenSearch" or "Elasticsearch", and the backend logic processing will be very efficient and fast.
-This is just based on the front-end perspective, optimizing from the perspective of reducing http requests

<!DOCTYPE html>
<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>Document</title>
</head>
<body>
    <input type="text" placeholder="Please enter the search content">
    <script>
        let timeID = null;
        document.querySelector('input').oninput = function(){
            /* Function anti-shake */
            //(1) Clear the previous timer clearTimeout(timeID) first
            //(2) Enable the anti-shake timer timeID = setTimeout(() => {
                console.log( this.value );
            }, 500);
        }
    </script>
</body>
</html>

Function throttling

Concept: Solve performance problems caused by high-frequency events; High-frequency events: In the page, some events are triggered very frequently.
For example: mouse movement, scroll wheel events.

Solution: If a user triggers an event multiple times in a row, it will only be triggered once within a specified time.

Example and solution code:

<!DOCTYPE html>
<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>Document</title>
    <style>
        body{
            height: 3000px;
        }
    </style>
</head>
<body>
    <script>
        let lastTime = null;
        
        let i = 1;
        window.onmousemove = function(){
            /* Function throttling */
            //(1) Determine the time interval between two trigger events let time = Date.now()
            if( time - lastTime >= 500 ){
                console.log('Number of mouse moves: ' + i++);
                //(2) This trigger time is used as the next reference interval lastTime = time
            }
        }
        // let j = 1;
        // window.onscroll = function(){
        // //(1) Determine the time interval between two triggering events// let time = Date.now()
        // if( time - lastTime >= 500 ){
        // console.log('Number of mouse scrolls: ' + j++);
        // //(2) This trigger time is used as the reference interval for the next time // lastTime = time
        // }   
        // }
    </script>
</body>
</html>

The above is the details of the sample code for JS function anti-shake and throttling in web project development. For more information about JS function anti-shake and throttling in web projects, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Analysis of JavaScript's anti-shake throttling function
  • Implementation and usage scenarios of JS anti-shake throttling function
  • How to understand JS function anti-shake and function throttling
  • A brief discussion on JavaScript throttling and anti-shake functions
  • A brief analysis of JavaScript function anti-shake and throttling
  • Detailed explanation of anti-shake and throttling of functions in JavaScript

<<:  MySQL merges multiple rows of data based on the group_concat() function

>>:  Implementation of Nginx configuration and access to local static resources in Mac environment

Recommend

JavaScript canvas to achieve meteor effects

This article shares the specific code for JavaScr...

KVM virtualization installation, deployment and management tutorial

Table of contents 1.kvm deployment 1.1 kvm instal...

How to open the port in Centos7

The default firewall of CentOS7 is not iptables, ...

Node uses async_hooks module for request tracking

The async_hooks module is an experimental API off...

Analysis of the method of setting up scheduled tasks in mysql

This article uses an example to describe how to s...

KTL tool realizes the method of synchronizing data from MySQL to MySQL

Use ktl tool to synchronize data from mysql to my...

HTML set as homepage and add to favorites_Powernode Java Academy

How to implement the "Set as homepage" ...

JavaScript implements simple calculator function

This article example shares the specific code of ...

Some notes on modifying the innodb_data_file_path parameter of MySQL

Preface innodb_data_file_path is used to specify ...

Implementation of Grid common layout

No gaps on both sides, gaps between each column w...

How to set static IP for Ubuntu 18.04 Server

1. Background Netplan is a new command-line netwo...

Briefly describe the MySQL InnoDB storage engine

Preface: The storage engine is the core of the da...

How to set up a shared folder on a vmware16 virtual machine

1. Set up a shared folder on the virtual machine:...

Summary of CSS counter and content

The content property was introduced as early as C...