Eliminate the front-end flicker devil: anti-shake technology in Vue

Preface

In the front-end world, user operations are like a storm, and our pages have to withstand these turbulent inputs. Sometimes, we want the page to respond after user input stops to avoid triggering operations frequently. At this time, Vue's anti-shake technology is like a time tunnel, taking us back to the peaceful past.

This blog will take you through time and space and reveal the mystery of anti-shake in Vue. Let us explore how this black technology can make the page more responsive and the user experience more comfortable.

What is anti-shake

Debouncing is a technology used in front-end development to control the execution frequency of functions. It reduces the number of function executions by combining multiple consecutively triggered function calls into one. The core idea of ​​anti-shake is to only execute a function once within a certain period of time and ignore other triggers within this period of time.

Basic principles of anti-shake:

  1. Set a timer: When the function is called, it does not execute immediately, but waits for a period of time.
  2. Reset the timer on repeated calls: If the function is called again within the waiting time, the previous timer is canceled and a new timer is reset.
  3. Function execution: When the waiting time is over, the function is executed.

Anti-shake application scenarios:

a. Input box input event:

  • Problem: The user continuously inputs in the input box, and each input triggers a search request.
  • Solution: Use anti-shake and wait for the user to stop typing for a period of time before triggering a search request to reduce the number of unnecessary requests.

b. Window resize event:

  • Problem: When the window is resized, the resize event is triggered frequently.
  • Solution: Use anti-shake and wait for the window size to stabilize before performing related operations to improve performance.

c. Button click event:

  • Problem: The button is clicked multiple times, triggering frequent operations.
  • Solution: Use anti-shake to ensure that the button click event handler is only executed once within a period of time.

d. Page scroll event:

  • Problem: When the page is scrolling, the scroll event is triggered frequently.
  • Solution: Use anti-shake and wait for scrolling to stop before performing related operations to improve performance.

Why do we need to let the function "cool down"?

  1. Performance optimization: Anti-shake can reduce the number of function executions, thereby improving performance. Especially in some frequently triggered events, resource consumption can be reduced by reducing the number of function executions.

  2. Reduce unnecessary network requests: In scenarios involving network requests, such as input box search suggestions, anti-shake can reduce unnecessary requests and improve user experience.

  3. Avoid repeated operations: Anti-shake can prevent users from triggering the same operation multiple times in a short period of time, ensuring that the corresponding logic is only executed at the right time.

  4. Solving the jitter problem: Some devices or browsers have touch or mouse jitter problems. Anti-shake can be used to smooth these jitter inputs, making the final triggered operation more stable.

Generally speaking, anti-shake is an effective strategy. By executing a function only once within a certain period of time, the execution frequency of the function can be better controlled, thus bringing some advantages in terms of performance and user experience.

Vue anti-shake principle

In Vue, the basic principle of anti-shake is to use setTimeout and clearTimeout to control the execution of functions. The following is a simple implementation example of anti-shake in Vue:

// 在Vue组件的methods中定义一个需要防抖的函数
methods: {
    
    
  // 防抖函数
  debounceFunction: function() {
    
    
    // 清除之前的定时器
    clearTimeout(this.timer);

    // 设置新的定时器
    this.timer = setTimeout(() => {
    
    
      // 在定时器结束时执行函数逻辑
      console.log('执行防抖函数的逻辑');
    }, 500); // 设置防抖的时间间隔,例如500毫秒
  }
}

In this example,debounceFunction is the function that requires anti-shake. When this function is called, it will first clear the previously set timer (if it exists), and then reset a new timer. The new timer will execute the function's logic after a certain period of time. If debounceFunction is called again within this period, the previous timer will be cleared and a new timer will be reset, thereby delaying the execution of the function.

This implementation mechanism ensures that only the last calldebounceFunction within a certain period of time will trigger the execution of the function, thus achieving the anti-shake effect.

In the Vue component, relevant initialization can be performed in the mounted life cycle hook, for example:

mounted() {
    
    
  this.timer = null; // 初始化定时器
}

In this way, the Vue component can achieve the anti-shake effect by callingdebounceFunction, which is suitable for some scenarios that need to limit the frequency, such as input events of input boxes, window size changes, etc.

How to prevent jitter in vue

Applying anti-shake technology in Vue is usually by using anti-shake functions in component methods. Here is a simple example demonstrating how to use antishake in a Vue component:

<template>
  <div>
    <input v-model="searchInput" @input="handleSearchInput" placeholder="Type to search">
    <p>Search result: {
   
   { searchResult }}</p>
  </div>
</template>

<script>
export default {
      
      
  data() {
      
      
    return {
      
      
      searchInput: '',
      searchResult: ''
    };
  },
  methods: {
      
      
    // 使用防抖函数处理搜索输入
    handleSearchInput: function() {
      
      
      // 在这里调用防抖函数,传入需要执行的实际搜索逻辑
      this.debounceSearch();
    },

    // 防抖函数
    debounceSearch: function() {
      
      
      // 清除之前的定时器
      clearTimeout(this.timer);

      // 设置新的定时器,延迟执行搜索逻辑
      this.timer = setTimeout(() => {
      
      
        // 实际的搜索逻辑,这里可以调用搜索接口等
        this.searchResult = `Searching for: ${ 
        this.searchInput}`;
      }, 500); // 设置防抖的时间间隔,例如500毫秒
    }
  },
  mounted() {
      
      
    this.timer = null; // 初始化定时器
  }
};
</script>

In this example, we have an input box for search, listen to user input through the @input event, and call the handleSearchInput method. The handleSearchInput method then calls the anti-shake function debounceSearch. This anti-shake function is used to control the execution frequency of the search logic.

The anti-shake functiondebounceSearch sets the timer throughsetTimeout to ensure that the search logic is executed only after the user stops inputting for a period of time. If the user continues to enter during this period, the previous timer will be cleared and a new timer will be reset, thereby delaying the execution of the search logic.

The anti-shake interval in this example is 500 milliseconds. You can adjust this value according to actual needs. This anti-shake technology can effectively reduce the number of searches that are triggered when frequent input into the input box, improving performance and user experience.

Anti-shake application scenarios

Anti-shake has many application scenarios in actual projects, mainly to improve performance and user experience by controlling the execution frequency of functions. The following are some common anti-shake application scenarios:

1. Input box search:

When typing text into the search box, anti-bounce can be used to ensure that the search request is only triggered after the user has stopped typing for a period of time. This reduces unnecessary requests and improves performance. This is especially useful in search scenarios for large data sets.

// 输入框搜索的防抖处理
handleSearchInput: debounce(function() {
    
    
  // 执行搜索逻辑
  // ...
}, 500)

2. Window resize event:

The window resize event (resize) is frequently fired when the user resizes the browser window. Using anti-shake can ensure that the relevant logic is only executed after the user stops resizing the window for a period of time, improving performance.

// 窗口大小调整事件的防抖处理
handleResize: debounce(function() {
    
    
  // 执行窗口大小调整逻辑
  // ...
}, 300)

3. Button click event:

In some scenarios, buttons may be clicked frequently by users. Using anti-shake can ensure that only the last click triggers the corresponding operation, avoiding unnecessary repeated executions.

// 按钮点击事件的防抖处理
handleButtonClick: debounce(function() {
    
    
  // 执行按钮点击逻辑
  // ...
}, 500)

4. Scroll event:

The page scroll event (scroll) is triggered when the user scrolls the page. Using anti-shake can ensure that scrolling-related logic is only executed after the user stops scrolling for a period of time, improving performance.

// 页面滚动事件的防抖处理
handleScroll: debounce(function() {
    
    
  // 执行滚动逻辑
  // ...
}, 200)

5. User input validation:

Perform real-time validation as users type, such as password strength checks. Anti-bounce can be used to delay validation operations to avoid triggering validation frequently while the user is still typing.

// 用户输入验证的防抖处理
validateInput: debounce(function() {
    
    
  // 执行输入验证逻辑
  // ...
}, 300)

In these scenarios, anti-shake technology can effectively reduce the number of unnecessary function executions and improve page performance and user experience. In actual projects, proper application of anti-shake can achieve smoother and more efficient interactions in some frequently triggered events.

Anti-shake vs throttling

Debouncing and throttling are both techniques for controlling the frequency of function execution, but they have some key differences in implementation and application.

Debouncing:

Principle: The core idea of ​​anti-shake is to merge multiple function calls by delaying a period of time to ensure that the function is only executed when there are no new function calls within a period of time. If there is a new function call during this period, the timing will be restarted.

Application scenarios: Suitable for operations that need to wait for a period of time before being executed, such as input box search, window resize events, etc. Anti-shake ensures that the corresponding action is only triggered after the user stops typing or stops resizing the window for a period of time.

Implementation example

function debounce(func, delay) {
    
    
  let timer;
  return function(...args) {
    
    
    clearTimeout(timer);
    timer = setTimeout(() => {
    
    
      func.apply(this, args);
    }, delay);
  };
}

Throttling:

Principle: The core idea of ​​throttling is to limit the number of executions of a function within a certain period of time to ensure that the function is only executed once within a specified time interval. If there are multiple function calls during this period, only the first call will take effect and subsequent calls will be ignored.

Application scenarios: Suitable for operations that require function execution within a certain time interval, such as scrolling events, button clicks, etc. Throttling can ensure that a function is only executed once within a certain period of time to avoid triggering too frequently.

Implementation example:

function throttle(func, delay) {
    
    
  let lastExecTime = 0;
  return function(...args) {
    
    
    const currentTime = Date.now();
    if (currentTime - lastExecTime >= delay) {
    
    
      func.apply(this, args);
      lastExecTime = currentTime;
    }
  };
}

Difference comparison:

  1. Execution time:

    • Anti-shake: The function will only be executed if there are no new function calls within a certain period of time.
    • Throttling: The function will only be executed once within a certain time interval, and whether there are new function calls will not be considered.
  2. Trigger time:

    • Anti-shake: Wait for a period of time after the last trigger of the event.
    • Throttling: Execute at the beginning of each interval.
  3. Applicable scene:

    • Anti-shake: Suitable for scenarios where you only care about the last trigger when triggering continuously, such as input box search.
    • Throttling: Suitable for scenarios that need to be executed within a certain period of time, such as scrolling events and button clicks.

how to choose:

  • Anti-shake: Suitable for scenarios that require waiting for a certain period of time before execution, and care about the result of the last trigger, such as input box search and window resize events.

  • Throttling: Suitable for scenarios that need to maintain execution within a certain time interval and care about each continuous trigger, such as scroll events and button clicks.

In actual applications, the choice of anti-shake or throttling depends on specific needs and business scenarios. If you are concerned about each consecutive trigger, you can choose throttling; if you only care about the result of the last trigger, you can choose anti-shake.

Best practices and considerations

  1. Understand the requirements: Before using anti-shake, make sure you clearly understand the business requirements. Make it clear whether you need to wait for a period of time before executing the function, or keep the function executing for a certain time interval.

  2. Choose an appropriate time interval: The effect of anti-shake and throttling is closely related to the set time interval. Based on specific needs, choose an appropriate time interval to achieve the best user experience and performance.

  3. Not suitable for scenarios with high real-time requirements: The anti-shake and throttling mechanisms will cause a certain delay, so it is not suitable for scenarios with high real-time requirements and immediate response. Scenes.

  4. Note that this points to: When using anti-shake in a Vue component, make sure that this inside the function points to the component instance. You can use arrow functions or use .bind(this) to bind this.

  5. Suitable for frequently triggered scenarios: Anti-shake and throttling are mainly used for frequently triggered events, such as input box input, scrolling events, etc. Used in these scenarios, it can effectively reduce the number of function executions and improve performance.

  6. Testing and debugging: When using anti-shake, it is important to conduct adequate testing and debugging. Ensure that the anti-shake logic can work properly under various conditions.

  7. Avoid overuse: Not all scenes are suitable for using anti-shake. In some scenarios that require instant response, anti-shake may cause user-perceived delays. Weigh your business needs and choose carefully whether to use image stabilization.

  8. Combined use: In some complex scenes, it may be necessary to use anti-shake and throttling in combination to meet different needs. For example, an input box needs to trigger a search when the user stops typing, and needs to update the search results every once in a while while the user continues typing.

  9. Consider disabling anti-shake: In some cases, it may be necessary to disable anti-shake. For example, when a certain condition is met, execute a function immediately without waiting for the anti-shake interval.

  10. Beware of memory leaks: If the anti-shake function is not cleaned up before the component is destroyed, it may cause a memory leak. Make sure resources such as timers are cleaned up when the component is destroyed.

Generally speaking, the purpose of using anti-shake and throttling is to better control the execution frequency of functions and improve performance and user experience. According to specific business needs and scenarios, carefully select and rationally configure anti-shake and throttling parameters.

Guess you like

Origin blog.csdn.net/m0_68390957/article/details/134485370