Method 1: Use the Lodash tool library
Lodash is a consistent, modular, and high-performance library of JavaScript utility tools.
(1) Use terminal to import the Lodash library
$ npm i -g npm $ npm i --save lodash
(2) Application
Example: Enter anti-shake in search box
In this example, we want the user to stop typing in the input box for 500 milliseconds before performing a search operation, avoiding frequent requests.
<input type="text" placeholder="Search..."> <script src="/npm/[email protected]/"></script> <script> // Suppose this is a function that performs search operations function performSearch(query) { ('Searching for:', query); // Here you can send an ajax request for search } // Use lodash's debounce function const debouncedSearch = _.debounce(function(event) { performSearch(); }, 500); // 500ms anti-shake time // Listen to input events in the input box ('search').addEventListener('input', debouncedSearch); </script>
Example: Rolling Event Throttle
In this example, we want to record the scroll event every 1 second when the user scrolls the page, avoiding frequent callback functions.
<div style="height: 2000px;">Scroll down to see the effect</div> <!-- Import throttle function--> <script src="/npm/[email protected]/"></script> <script> // This is a function that handles scrolling events function handleScroll() { ('Scroll event detected at:', new Date().toLocaleTimeString()); } // Use lodash's throttle function to trigger at most every 1 second const throttledScroll = _.throttle(handleScroll, 1000); // Listen to scroll events ('scroll', throttledScroll); </script>
- explain:
- When the user scrolls the page,
throttledScroll
The function will be triggered at most once in 1 second to avoid frequent callback functions being called during scrolling. - This optimizes the performance of page scrolling, especially when the callback function is more complex.
- When the user scrolls the page,
Example: Combining leading and trailing options
Suppose we want the function to be executed immediately when the user first triggers an event and again after stopping the triggering 1 second.
<input type="text" placeholder="Type something..."> <script src="/npm/[email protected]/"></script> <script> // Assume this is a function that processes input function handleInput(value) { ('Input value processed:', value); } // Use the debounce function and configure the leading and trailing options const debouncedInput = _.debounce(function(event) { handleInput(); }, 1000, { leading: true, trailing: true }); // Listen to input events in the input box ('input-field').addEventListener('input', debouncedInput); </script>
Method 2: Custom anti-shake and throttling functions
(1) Create a file in the utils folder, and define the anti-shake throttling function.
// Anti-shake functionexport function debounce(fn: Function, delay: number) { let timer: ReturnType<typeof setTimeout> | null = null; return function (this: any, ...args: any[]) { // Clear the previous timer if (timer) { clearTimeout(timer); } // Set a new timer timer = setTimeout(() => { (this, args); // Use apply to ensure that this and parameters are passed correctly }, delay); }; } // throttling functionexport function throttle(fn: Function, delay: number) { let lastTime = 0; return function (this: any, ...args: any[]) { const now = (); // If the last execution time has exceeded the specified time interval, the function will be executed if (now - lastTime >= delay) { lastTime = now; // Update the last execution time (this, args); } }; }
(2) Application
Anti-shake
- Method 1:
<template> <div> <input v-model="searchText" placeholder="Enter search content" /> <button @click="handleSubmit">submit</button> </div> </template> <script lang="ts" setup> import { ref } from 'vue'; import { debounce } from '@/utils/debounce'; // Introduce the anti-shake function you wrote yourself // 1. Declare responsive dataconst searchText = ref<string>(''); // 2. Anti-shake function, delay 1000 milliseconds to perform submission operationconst submitForm = (val: string) => { ('Submitted search value:', val); // Perform the submission operation here}; // 3. Use anti-shake function to wrap the submission operationconst handleSubmit = debounce(() => { submitForm(); // Use the currently entered value to perform the submission operation}, 1000); // The anti-shake delay is set to 1000 milliseconds </script>
- Method 2:
<template> <div> <input v-model="searchText" placeholder="Enter search content" /> <button @click="submitForm(searchText)">submit</button> </div> </template> <script lang="ts" setup> import { ref } from 'vue'; import { debounce } from '@/utils/debounce'; // Introduce the anti-shake function you wrote yourself // 1. Declare responsive dataconst searchText = ref<string>(''); // 2. Define the submission form operationconst submitForm = debounce((val: string) => { ('Submitted search value:', val); // Perform the submission operation here}, 1000); // The anti-shake delay is set to 1000 milliseconds </script>
Throttle
<template> <div @scroll="handleScroll" style="height: 300px; overflow-y: scroll;"> <!-- Simulation content,Exceed container height to enable scrolling --> <div style="height: 1000px;">Scroll content</div> </div> </template> <script lang="ts" setup> import { throttle } from './debounce'; // Introduce throttling function // 1. Define the scroll event handling function (throttling)const handleScroll = throttle(() => { ('Scrolling event triggers'); // Handle scrolling events here, such as loading more content}, 200); // Only once every 200 milliseconds </script>
<template> <div @scroll="handleScroll" style="height: 300px; overflow-y: scroll;"> <!-- Simulation content,Exceed container height to enable scrolling --> <div style="height: 1000px;">Scroll content</div> </div> </template> <script lang="ts" setup> import { throttle } from './debounce'; // Introduce throttling function // 1. Define the scroll event handling function (throttling)const handleScroll = throttle(() => { ('Scrolling event triggers'); // Handle scrolling events here, such as loading more content}, 200); // Only once every 200 milliseconds </script>
Application scenarios
Anti-shake (debounce):
His hands trembled. . . I ordered several times and only executed once within a certain period of time. (You are old and your hands are shaking)
- Function: The callback function will only be executed after the user stops triggering the event for a period of time.
- Application scenarios: Input box search, window resize, form submission, etc.
Throttle:
For example, after clicking twice to refresh the list page, it will not execute it directly twice immediately. It is before a certain time interval you define, and then execute it first and then execute it the second time.
- Function: Only execute the function once within the specified time interval. If triggered frequently, function execution is limited to execution at most once per interval.
- Application scenarios: scroll event, mouse movement event, resize event, etc.
Attachment: Installation and introduction issues
Problem Description: Newbie may encounter installation and introduction issues when using Vue-lodash.
Solution steps:
Make sure Vue and lodash are installed correctly.
Install Vue-lodash using npm or yarn:
npm install --save vue-lodash lodash
or
yarn add vue-lodash lodash
Introduce Vue-lodash and lodash in your Vue project:
import Vue from 'vue'; import VueLodash from 'vue-lodash'; import lodash from 'lodash';
Summarize
This is the article about the Lodash tool library for VUE front-end anti-shake throttling. For more related content on VUE front-end anti-shake throttling, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!