[Essay 3] An article clarifies throttling, anti-shake and application scenarios

foreword

防抖节流Many people are particularly prone to confuse concepts. Today, an article teaches you to thoroughly clarify the concepts and application scenarios.

Let's start with the common ground

Both the anti-shake and throttling functions are used to limit the execution frequency of the function, so that the response speed caused by the high trigger frequency of the optimization function cannot keep up with the trigger frequency, resulting in delays, freezes, and other errors. It is a common front-end performance optimization technique.

But the application scenarios are different

anti shake

Anti-shake is usually used to deal with some high-frequency triggering events , such as the user continuously clicking the button and frequent input in the input box.

When the user clicks the button too quickly, the interface is called multiple times due to repeated clicks; or the interface is called as soon as the text in the input box changes, resulting in multiple calls to the interface.

At this point, we definitely want to call the interface only once even if the button is clicked multiple times; we also don’t want the input box to send a request every time a letter is entered, so that the page will send requests frequently, which greatly wastes resources.

Anti-shake can be used to send the request after the user completes the input, or to avoid repeatedly clicking the button to repeat the request, reduce the number of function executions and interface calls, and avoid performance waste caused by frequent UI updates or sending requests.

To put it simply: anti-shake is the final say. Its core is: within a certain period of time, no matter how many callbacks are triggered, only the last one is recognized.

Four words summary: Waiting for you to the end

// 写一个简单的防抖函数
/**
 *	@param fn:需要用来防抖的方法,是一个回调
 *	@param wait: 时间间隔
 *	对于短时间内连续触发的事件,防抖可以用来在某个时间内(wait),事件处理函数只执行最后一次
 */
export const debounce = (fn: any, wait: num) => {
    
    
	let timer: any = null
	return () => {
    
    
		if(timer) {
    
    
			clearTimerout(timer)
		}
		timer = setTimeout(fn, wait)
	}
}

throttling

Throttling: It refers to the execution of events that are triggered continuously at intervals . The time involved in throttling mainly refers to the interval of time execution.

Usually used in some high-frequency events, such as mouse scrolling, window resize, scroll bar sliding and other operations. In this case, we hope that these events can be triggered at a certain frequency (to be triggered multiple times), but not every event is triggered. The throttling function can specify that this method is only executed once in a certain time interval. This can reduce the number of executions of the function and optimize performance.

To give a simple example, when the user drags the scroll bar, if an event is triggered every time the scroll is made, the page will update the UI very frequently, causing freezes. Use the throttling function to limit the trigger frequency and improve page fluency.

To put it simply: throttling is the first time to have the final say . Its core is: within a certain period of time, no matter how many callbacks are triggered, only the first time is recognized.

timestamp throttling

// 时间戳节流实现
function throttle(fn: any, wait: number) {
    
    
  let prev = 0;
  return function(...args) {
    
    
    const now = Date.now();
    if (now - prev >= delay) {
    
    
      fn(...args);
      prev = now;
    }
  };
}

In the throttling function above, each time an event is triggered, it is judged whether the interval between the current time and the last triggered event exceeds the specified time interval. If so, the time processing function is waitexecuted fnand the last triggered event is updated to the current time .

Write a method to test the throttling function above.

// 测试
function log() {
    
    
  console.log('hello world');
}

const throttledLog = throttle(log, 3000);

setInterval(throttledLog, 50);

In the above code, it was originally called once every 50 milliseconds throttleLog, but because the throttling interval of 3000 milliseconds is set, in fact, the log function will only be executed every 3000 milliseconds.

Using the above timestamp throttling , there is another way to write: limit the number of trigger events within a certain period of time: that is, we define a limit on the number of calls within a certain time interval , but we won’t say much here.

timer throttling

// 定时器节流
export const throttle = (fn: any, wait: number) => {
    
    
	let timer: any = null;
	return function(...args) {
    
    
		if(!timer) {
    
    
			timer = setTimeout(function() => {
    
    
				fn(...args);
				timer = null
			}, wait)
		}
	}
}

1. In throttling, why should timer be equal to null?

First of all, we need to know one thing: the timer has a return value, and the return value is the ID number of the current timer . clearTimeout(timer) will clear the timer function, but will not change the id value. From the figure below, we can see that using clearTimeout will not change the ID number of the timer, but the timer can be turned off.


If we do not set the timer to null, but directly set a new timer ID, then the previous timer cannot be cleared, which will cause multiple timers to execute at the same time, and the effect of throttling cannot be achieved. Therefore, before executing the timer function each time, set the timer to null to ensure that the previous timer can be cleared correctly when the next event is triggered.

insert image description here

Guess you like

Origin blog.csdn.net/qq_41131745/article/details/129635083
Recommended