What is throttling anti-shake? how to use? Use case, usage scenario?

Disclaimer: It is purely Xiaobai's personal understanding. If there is something wrong, criticism and correction are welcome.

Table of contents

Example complete code Demo.html

semantic interpretation

Anti-shake code implementation

throttling code implementation


Example complete code Demo.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>

	<button onclick="btn()">回城(需要5秒)</button>
	<button onclick="btn2()">技能(2秒冷却)</button>

</html>
<script>
	// 防抖
	let btn = debounce(goHome)

	function goHome() {
		console.log("成功回到泉水~~")
	}

	function debounce(fun) {
		let timer = null
		return function() {
			clearTimeout(timer)
			timer = setTimeout(() => {
				let args = arguments
				fun.apply(this, args)
			}, 5000)
		}
	}
	// 节流
	let btn2 = throttle(use,2000)

	function use() {
		console.log("二技能已释放")
	}

	function throttle(fun,time) {
		let t1 = 0
		return function() {
			let t2 = new Date()
			if (t2 - t1 > time) {
				fun.apply(this, arguments)
				t1 = t2
			}
		}
	}
</script>

semantic interpretation

Have played both LOL or Glory of Kings.

Going back to the city to mock this trick, right? Can you use your skills ?

1: Then I can say that the event of returning to the city is anti-shake . Suppose it takes 5 seconds to return to the city, and you keep returning to the city to taunt the opponent, even if your behavior lasts for 10 seconds, you will not be able to return to the fountain. If you stop taunting after 3 seconds, then recalculate from the 3rd second , after 5 seconds you can return to the fountain.

防抖It is a way to improve performance that is performed only once in continuous operations (input, click, etc.).

2: Then releasing the skill is throttling . Suppose the CD (cooling) of the second skill is 2 seconds, then you click the second skill and the skill is released. No matter how many times you click the skill button within 2 seconds, you will not release the skill again. That is to say, you can only release the skill 3 times within 6 seconds, and the 4th skill can only be released after 6 seconds have passed completely.

In daily development, we roll the mouse wheel to monitor the position of the scroll bar, which will be used to prevent multiple clicks on the button. To put it bluntly, throttling means that it will only be executed once when triggered at intervals


Anti-shake code implementation

1: First, we simulate a button to return to the city and bind an event to it. The final effect is that we want to simulate the event of returning to the city after 5 seconds after clicking.

 

<button onclick="goHome()">回城(需要5秒)</button>
    function goHome() {
        console.log("成功回到泉水~~")
    }

Assuming that the printed content is used to simulate the real result, it is obviously unreasonable at this time, because it means that I will return to the spring as soon as I click.


2: It is easy to think of using a timer to realize the operation of returning to the spring with a delay of 5 seconds. We define a function debounce and pass in a method as a parameter. When we call debounce(goHome), we can print out "Successfully returned to the spring~~" after 5 seconds.

<button onclick="btn()">回城(需要5秒)</button>
    let btn = debounce(goHome)

	function goHome() {
		console.log("成功回到泉水~~")
	}

    function debounce(fun) {
        return function() {
             setTimeout(() => {
                fun()
            }, 5000)
        }
    }

Now the purpose of the delay is achieved, but each click will add a new one setTimeout, and it cannot achieve the effect that we only execute once for multiple clicks. When I click 2 or more times in a row, multiple timers are actually triggered. After a certain period of time, as many times as I click, there will be as many times as "successfully returned to the spring~~" output.

This is obviously not what I want (because if so, I can't go back to the city to mock).

It can be used at this time clearTimeout. We hope that after the button is clicked, that is, debouncewhen the button is executed, the previous one will be setTimeoutcleared and then the timing will be restarted.

	function debounce(fun) {
		let timer = null
		return function() {
			clearTimeout(timer)
			timer = setTimeout(() => {
				fun()
			}, 5000)
		}
	}

Now an anti-shake function is ok, but if we goHome()print , thiswe will find that we thisare pointing Windowto it. Use applyto change thisthe pointer, and another parameter that needs to be considered to execute the function, because different functions will definitely have different parameters passed in, and we can use argumentsprocessing for the parameters.

	function debounce(fun) {
		let timer = null
		return function() {
			clearTimeout(timer)
			timer = setTimeout(() => {
				let args = arguments
				fun.apply(this, args)
			}, 5000)
		}
	}

throttling code implementation

1: Similarly, we simulate a skill release button, and also bind an event. The final effect is that we want to realize that only one skill event can be released within 2 seconds of simulation.

<button onclick="btn2()">技能(2秒冷却)</button>

2: The specific thinking is similar to anti-shake, so I won’t write it specifically

	// 节流
	let btn2 = throttle(use,2000)

	function use() {
		console.log("二技能已释放")
	}

	function throttle(fun,time) {
		let t1 = 0
		return function() {
			let t2 = new Date()
			if (t2 - t1 > time) {
				fun.apply(this, arguments)
				t1 = t2
			}
		}
	}

Here we record two times: t1表示the initial time and t2表示the current time. If the current time is far from the previous time, the initial time is greater than the set time 2000.

Then we can execute fun()and change the initial time to the time of this execution, so that every time we execute it, t1it becomes the time of the last execution. Such a throttling function is completed.

Guess you like

Origin blog.csdn.net/weixin_50656154/article/details/126611428
Recommended