Vue practical skills: Encapsulate global anti-shake and throttling functions from scratch

foreword

Have you ever experienced unresponsiveness caused by users frequently clicking buttons or scrolling pages? This is because the events are fired continuously, causing performance degradation. In this article, I will introduce the anti-shake and throttling strategies in Vue , and show you how to encapsulate the global anti-shake throttling function to avoid frequent triggering events and improve the response speed of the page.


package file

The implementation idea of ​​the package file is as follows:

  • First, we need to define two functions: anti-shake function and throttling function. The purpose of these two functions is to reduce performance problems caused by frequently triggering an event;
  • The implementation idea of ​​the anti-shake function is to create a timer variable to delay the execution of the function. When an event is triggered, the previous timer is first cleared, and then a new timer is created to delay the execution of the function. If the event is triggered again during the delay period, the previous timer will be cleared and the timer will be recreated;
  • The implementation idea of ​​the throttling function is to create a timer variable to limit the calling frequency of the function. When the event is fired, the function is executed immediately if the timer variable does not exist, and a timer is created that resets the timer variable after the specified time. If the event is triggered again while the timer is not expired, it will be invalid and the function will not be executed again;
  • Using closures inside the function can save the state of the variable so that the correct variable value can be accessed every time an event is triggered;
  • Finally, exportexport the anti-shake function and throttling function through the statement for use in other places.

The purpose of the package file is to encapsulate the anti-shake and throttling logic in a separate file, which is convenient for reuse in different projects, and makes the code more readable and maintainable.

// 防抖函数
function debounce(func, wait, immediate) {
    
    
    let timeout; // 定义一个计时器变量,用于延迟执行函数
    return function (...args) {
    
     // 返回一个包装后的函数
        const context = this; // 保存函数执行上下文对象
        const later = function () {
    
     // 定义延迟执行的函数
            timeout = null; // 清空计时器变量
            if (!immediate) func.apply(context, args); // 若非立即执行,则调用待防抖函数
        };
        const callNow = immediate && !timeout; // 是否立即调用函数的条件
        clearTimeout(timeout); // 清空计时器
        timeout = setTimeout(later, wait); // 创建新的计时器,延迟执行函数
        if (callNow) func.apply(context, args); // 如果满足立即调用条件,则立即执行函数
    };
}

// 节流函数
function throttle(func, wait) {
    
    
    let timeout; // 定义一个计时器变量,用于限制函数调用频率
    return function (...args) {
    
     // 返回一个包装后的函数
        const context = this; // 保存函数执行上下文对象
        if (!timeout) {
    
     // 如果计时器不存在
            func.apply(context, args); // 执行函数
            timeout = setTimeout(() => {
    
    
                timeout = null; // 清空计时器变量
            }, wait); // 创建计时器,在指定时间后重置计时器变量
        }
    };
}

export {
    
    
    debounce,
    throttle
}; // 导出防抖函数和节流函数

Global import

main.js

// 引入防抖节流函数文件
import {
    
     debounce, throttle } from './utils/dbucTrtl.js';
// 在Vue实例上扩展全局方法
Vue.prototype.$debounce = debounce;
Vue.prototype.$throttle = throttle;

use file

When the user clicks a button, we can use the anti-shake function to prevent the user from misoperation causing the same event to be triggered multiple times. The throttling function can limit the frequency of the user clicking the button to prevent repeated operations caused by continuous clicking.

Here's an example of a debounce and throttling function that uses click events:

<template>
  <div>
    <button @click="debouncedClick">点击触发防抖函数</button>
    <button @click="throttledClick">点击触发节流函数</button>
  </div>
</template>

<script>
export default {
      
      
  created() {
      
      
    // 使用防抖函数处理点击事件
    this.debouncedClick = this.$debounce(this.handleClick, 1000);

    // 使用节流函数处理点击事件
    this.throttledClick = this.$throttle(this.handleClick, 1000);
  },
  methods: {
      
      
    handleClick() {
      
      
      console.log("按钮点击事件处理中...");
      // 在这里编写具体的点击事件处理逻辑
    },
  },
};
</script>

In the above example, there are two buttons, which are bound to @clickthe event and call different processing methods. debouncedClickUse the anti-shake function to handle the click event, and delay the execution of handleClickthe method to avoid triggering multiple events caused by the user's continuous click. throttledClickUse the throttling function to handle the click event, limit the frequency of the user clicking the button, and ensure that the event is only triggered once within a certain period of time. Through the application of these anti-shake and throttling functions, user misoperations can be avoided and user experience can be improved.


achieve effect

insert image description here


scenes to be used

Anti-shake usage scenarios:

  • Input box search: When the user enters text in the input box, anti-shake can be used to delay the execution of the search operation, and only perform the search operation after the user stops typing for a period of time, reducing meaningless search requests;
  • Window adjustment/scrolling events: During window resizing or scrolling, anti-shake can prevent events from being triggered frequently, reducing unnecessary calculation and redrawing operations;
  • Form verification: When verifying form input, anti-shake can delay the execution of the verification operation, and only perform verification after the user completes the input for a period of time, avoiding frequent verification operations;
  • Button clicks: When the user clicks a button, anti-shake can be used to prevent the user from misuse or repeated clicks, ensuring that only one action is performed.

Throttling usage scenarios:

  • Page scrolling: During page scrolling, throttling can be used to limit the frequency of triggering callback functions and reduce the number of event processing to avoid excessive calculation and rendering operations;
  • Mouse move in/out event: When monitoring the event of mouse moving in or out of an element, throttling can limit the triggering frequency of the event, avoiding frequent function calls due to fast entering and leaving;
  • Swipe operation: When monitoring the slide operation, throttling can limit the trigger frequency of the callback function, so as to better control the slide effect and animation display;
  • Request sending: When sending network requests, throttling can be used to control the frequency of requests to avoid overloading the server by sending too many requests.

In general, anti-shake is suitable for use in scenarios that need to avoid frequent trigger events, while throttling is suitable for use in scenarios that control the frequency of function calls and avoid excessive function calls.


Summarize

Debounce and throttling are two common optimization techniques used to control how often events are fired to improve performance and user experience.

Anti-shake It limits a function to be executed only once after consecutive trigger events. The debounce function sets a timer when the event is triggered. If the event is triggered again within the specified time, the timer is cleared and reset. Only when the event stops triggering for a period of time, the timer will execute the corresponding function. Anti-shake is often used to handle the callback function when the user frequently operates, such as triggering a search operation when typing in an input box. Through anti-shake, unnecessary function calls can be reduced and performance can be improved.

Throttle which controls how often the function fires over a period of time. When the event is triggered, the throttling function will execute the corresponding callback function and set a timer to limit that the event cannot be triggered again within a period of time. Only after the specified time interval has elapsed can the function be triggered again. Throttling is often used to handle callback functions when users frequently trigger events, such as triggering certain effect animations when the page is scrolled. Through throttling, you can limit the frequency of function calls to prevent performance problems caused by frequent triggering of events.

To sum up, anti-shake and throttling are techniques to control the frequency of function execution. Anti-shake limits the function to be executed only once after consecutive trigger events, while throttling controls can only trigger a function once in a period of time. Both technologies optimize performance and provide a better user experience.


related suggestion

[Global optimization] The WeChat applet globally encapsulates the anti-shake throttling function, making your program more efficient and smooth

おすすめ

転載: blog.csdn.net/Shids_/article/details/131591322