Debounce and throttling of js functions

Table of contents

Preface:

Anti-shake (debounce)

Throttle

 Code examples

appendix:

Regarding the pointer analysis of context(this) in the throttling/anti-shake function:

This in the anti-shake function points to

this in the throttling function points to


Preface:

When we develop, there will be many scenarios that frequently trigger events, such as the search box sending requests in real time, onmousemove, resize, onscroll, etc. Sometimes, we cannot or do not want to trigger events frequently. What should we do? At this time, you should use function anti-shake and function throttling!

Anti-shake (debounce)

Debounce refers to executing only the last triggered event within a certain period of time. It is suitable for situations where you only care about the result of the last trigger during the continuous triggering of events.

For example, when users continuously enter search keywords, we can use anti-shake to reduce the number of network requests. A network request is sent for the search after the user has stopped typing for a period of time.

The following is a simple JavaScript example of implementing an anti-shake function:

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

This debounce function accepts two parameters: func is the function to be executed, and delay is the delay time. Each time an event is triggered, it clears the previously set timer and resets a newtimer. If the event is triggered again within the delay time, the timer is cleared and reset. The function will only be executed if the delay time has elapsed without the event being triggered again.

Throttle

Throttle refers to fixing the frequency of executing events within a certain period of time. It is suitable for situations where a certain execution frequency needs to be maintained during the continuous triggering of events.

For example, when the user continuously scrolls the page, we can use throttling to limit the frequency of processing scroll events to avoid excessive calculation and rendering.

The following is a simple JavaScript example of implementing a throttling function:

function throttle(func, delay) {
  let timer;
  return function() {
    if (!timer) {
      timer = setTimeout(() => {
        func.apply(this, arguments);
        timer = null;
      }, delay);
    }
  };
}

This throttle function accepts two parameters: func is the function to be executed, and delay is the delay time. Each time an event is triggered, it will check if there istimer, if it does not exist it will set a new timer and after the delay time expires Execute function. This ensures that the function is only executed once during the delay time.

To sum up, anti-shake and throttling are techniques used to optimize performance and control the frequency of event triggering. Anti-shake is suitable for situations where you only care about the last trigger result, while throttling is suitable for situations where a certain execution frequency needs to be maintained.

 Code examples

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			body {
				height: 200vh;
				/* 为了触发滚动事件,增加页面高度 */
			}
		</style>
	</head>
	<body>
		<h1>防抖和节流示例</h1>

		<script>
			// 防抖函数
			function debounce(func, delay) {
				let timer; // 定时器变量
				return function() {
					clearTimeout(timer); // 清除之前的定时器
					timer = setTimeout(() => {
						func.apply(this, arguments); // 延迟时间结束后执行函数
					}, delay);
				};
			}

			// 节流函数
			function throttle(func, delay) {
				let timer; // 定时器变量
				return function() {
					if (!timer) {
						timer = setTimeout(() => {
							func.apply(this, arguments); // 延迟时间结束后执行函数
							timer = null; // 清空定时器变量
						}, delay);
					}
				};
			}

			// 示例函数:处理滚动事件
			function handleScroll() {
				console.log("处理滚动事件");
			}

			// 使用防抖函数包装处理滚动事件的函数
			const debouncedHandleScroll = debounce(handleScroll, 200);

			// 使用节流函数包装处理滚动事件的函数
			const throttledHandleScroll = throttle(handleScroll, 200);

			// 监听滚动事件,并调用相应的处理函数
			window.addEventListener("scroll", debouncedHandleScroll);
			// 如果要使用节流函数,可以将上面一行改为下面这行
			// window.addEventListener("scroll", throttledHandleScroll);
		</script>
	</body>
</html>

appendix:

Regarding the pointer analysis of context(this) in the throttling/anti-shake function:

In anti-shake and throttling functions, the direction of this is very important. Let’s analyze them separately:

This in the anti-shake function points to

In the anti-shake function, if not processed, this will point to the object currently calling the anti-shake function (such as the window object). Therefore, we need to explicitly specify the value of this using the Function.prototype.apply() or Function.prototype.call() method.

For example, when the handleInput function in the following code is executed, this will point to the input element itself:

<input type="text" oninput="debouncedHandleInput.call(this, event)">

This here represents the current input element. Explicitly specify this as this in the debouncedHandleInput function via the call() method.

this in the throttling function points to

In the throttling function, the point of this is slightly different from that of the anti-shake function. In the throttling function, this should usually point to the target element of the event (such as the button element), not the object currently calling the throttling function (such as the window object).

For example, when the handleClick function in the following code is executed, this will point to the button element itself:

<button onclick="throttledHandleClick(event)">点击</button>

This here represents the current button element. In the throttledHandleClick function, you can use this to obtain the attributes of the target element, modify the style, and other operations.

It should be noted that when using arrow functions to define anti-shake and throttling functions, the pointer of this will not change and still points to this in the outer scope.

In summary, the this pointer in anti-shake and throttling functions should be clearly specified based on the actual situation.

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/134619789