About the application of anti-shake and throttling in front-end development

Debounce and throttling are essentially designed to optimize the way users execute code at high frequencies.

Common high-frequency operations in front-end development include, for example, if the user keeps clicking the submit button of the form to submit, the browser will keep sending http requests, which wastes a lot of bandwidth resources and also increases the pressure on the server. Another example is that when resize, scroll, keypress, mousemove and other events on the browser are triggered, the callback function bound to the event will be continuously called, which greatly wastes resources and reduces application performance. In order to optimize the experience, such events need to be processed To limit the number of calls, you can use anti-shake debounce and throttling methods to reduce the frequency of calls.

Below we give examples of the differences, advantages and disadvantages between the two:

Debounce:
As the name suggests, it is used to prevent hand shake from triggering events multiple times. The main method of implementation is to set a delayer. Only the last trigger of high-frequency triggers in a short period of time is successful.

Explanation: For example, after clicking submit, set a timer and send the request every 1 second. If there are multiple requests within 1 second, the timer will be cleared and the request will be resent after 1 second. In other words, no matter how many times you click submit within 1 second, the last delay will always be cleared and then your own request will be made.
Code:

	/**
	**@param{fun: function} 需要防抖执行的函数
	**@param{delay: number} 延迟时间
	*/
	const debounce = (func, delay = 1000) => {
    
    
		let timer = null   // 存储定时器的timerId
		return function(...args) {
    
    
			// 在每一次调用函数时,都清除上一次的定时器
			if (timer) clearTimeout(timer)
			// 开启一个定时器
			timer = setTimeout(() => {
    
    
				func.apply(this, args)
			}, delay)
		}
	}

Advantages: No matter how messy you are, only the last request will succeed.
Disadvantages: The response time is too long, that is, if you keep clicking, it will keep clearing the timer and resending the request, so you need to wait until it stops before sending the request.

Throttle:
As the name suggests, it saves traffic and sets a status lock. Only the first trigger of high-frequency triggers in a short period of time is successful.

Explanation: Throttling is to set a state lock, such as setting a state as a state lock. The lock is closed at the beginning, that is, the state value is set to false. When you click, the state will be judged. If the state is false and it is not locked, then a request will be initiated and the state will be locked, that is, the state will be set to true. If you continue to click, judge the state and find that the state is locked, then no request will be initiated, and the click will be invalid. When the request is completed, the state is set to false, and then the state at this time is judged to be false before the next request, and a new round of requests can be sent.
Code:

let state = true
ele.onclick = function() {
    
    
	// 点击第一次发送请求
	if (state) {
    
    
		// 发送请求立即给 state 赋值为 false
		state = false
		// 异步请求
		setTimeout(() => {
    
    
			console.log('xhr响应成!')
			// 在响应回调中将锁打开,等请求返回响应才可以触发第二次请求
			state = true
		}, 1000)
	}
};

It can be seen that when the first request is sent, the conditions for triggering the function are not met.
The purpose of anti-shake and throttling is to reduce the frequency of callback execution and save computing resources.
Function anti-shake, after the end of a continuous operation, handles the callback, using setTimeout and clearTimeout to implement.
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.
In short, the summary in one sentence is:
anti-shake is to perform the operation after a period of time. If it is triggered repeatedly within a period of time, the timing will be restarted.
Throttling only runs once within a period of time. If it is triggered repeatedly within a period of time, it will only take effect once.

Guess you like

Origin blog.csdn.net/kirinlau/article/details/127099026