Hand-write an anti-shake throttling function and its usage scenarios

 

Anti-shake and throttling are performance optimization methods
What is anti-shake? Anti-shake: Events are triggered frequently within a unit time, and only the last time is executed. Main application scenarios of anti-shake:
  • Search box search input. The user only needs to complete the last input before sending the request.
  • Mobile phone number and email verification input detection
What is throttling? Throttling: within a unit time, events are triggered frequently and executed only once. Main application scenarios of throttling:
  • High-frequency events such as resize events and scroll events
  • Mobile phone number and email verification input detection

Same point:

  • All can be achieved by using setTimeout
  • Reduce callback execution frequency. Save computing resources

difference:

  • Function anti-shake, after the end of a continuous operation, handles the callback, using clearTimeout and setTimeout to achieve. Function throttling, in a continuous operation, is only executed once per period of time, and is used in higher frequency events to improve performance.
  • Function anti-shake focuses on events that are triggered continuously for a certain period of time and is only executed once at the end, while function throttling is only executed once within a period of time.

Essentially, it is a means of optimizing code that is executed frequently.

For example: browser's resize, scroll, keypress, mousemove , etc. When an event is triggered, the callback function bound to the event will be continuously called, which greatly wastes resources and reduces front-end performance

In order to optimize the experience, it is necessary to limit the number of calls to this type of event. For this, we can use throttle (dithering) and debounce ( To reduce the frequency of calls

definition
  • Throttling: only runs once in n seconds. If triggered repeatedly within n seconds, only one time will take effect.
  • Anti-shake: Execute the event after n seconds. If it is triggered repeatedly within n seconds, the time will be restarted.

A classic metaphor:

Imagine the elevator under the building where you go to work every day. Completing an elevator transport is analogized to the execution and response of a function.

Assume that the elevator has two operation strategies debounce and throttle, and the timeout is set to 15 seconds, regardless of the capacity limit

After the first person in the elevator comes in, he will be transported on time after 15 seconds. This is throttling.

After the first person in the elevator comes in, wait 15 seconds. If someone else comes in during the process, wait for 15 seconds to re-time until the transportation starts after 15 seconds. This is anti-shake

code
// 防抖函数
function debounce(func, delay) {
  let timer;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      func.apply(context, args);
    }, delay);
  };
}

// 节流函数
function throttle(func, delay) {
  let timer;
  return function () {
    const context = this;
    const args = arguments;
    if (!timer) {
      timer = setTimeout(function () {
        func.apply(context, args);
        timer = null;
      }, delay);
    }
  };
}

Scenario 1: Search box real-time search

In this scenario, we hope that when the user enters the search keyword, the search request will not be triggered immediately, but will wait for the user to stop typing for a period of time before initiating the request. This is a typical anti-shake use case

// HTML结构
<input type="text" id="searchInput">
<div id="searchResults"></div>

// JavaScript代码
const searchInput = document.getElementById("searchInput");
const searchResults = document.getElementById("searchResults");

function performSearch(query) {
  // 模拟搜索操作,实际中可以发起AJAX请求等
  searchResults.innerHTML = `正在搜索:${query}`;
}

const debouncedSearch = debounce(performSearch, 300); // 防抖处理搜索函数

searchInput.addEventListener("input", function () {
  const query = this.value;
  debouncedSearch(query); // 使用防抖函数处理输入事件
});

Scenario 2: Scroll event

In this scenario, we hope that when users scroll the page, performance problems will not be caused by frequent triggering of scroll events. This is a typical throttling use case.

// JavaScript代码
function handleScroll() {
  // 处理滚动事件,例如更新UI等
}

const throttledScroll = throttle(handleScroll, 200); // 节流处理滚动事件

window.addEventListener("scroll", throttledScroll); // 使用节流函数处理滚动事件

Guess you like

Origin blog.csdn.net/weixin_53818172/article/details/132674784