Function anti-shake

<!--
            1. What is function anti-shake?
                It means that after an event is triggered, it can only be executed once within the specified time. If the event is triggered again within the specified time, the specified time will be restarted. For example:
                when you When in the elevator,
                        the elevator starts counting down for 5 seconds to close the door.
                        Within 5 seconds, if
                        a person suddenly comes,
                        the door will automatically open, and
                        the elevator will restart the timer for 5 seconds.
                        If another person comes within 5 seconds,
                        the elevator will restart the timer for 5 seconds.
                        If another person comes within 5 seconds,
                        the elevator will restart the timer for 5 seconds.
                        Start the countdown 5 4 3 2 1,
                        when no one comes, the elevator closes the door and starts running
                        
            2. Why do you need to perform function anti-shake?
                If you make an input box, the user enters the value in it and then requests data from the server
                The user can't input a value to request the server once, so the server can't stand it, and the server is also confused
                
 


            3. The principle of function anti-shake
                is actually to use the timer.
                Assuming that I have been inputting content, I will not request data. If I have finished inputting, I will ask for another input
                . If I do not request data, I will input again
         .

Code:

<input type="text"/>
		 <script type="text/javascript">
		 	//代码实现
			const inp = document.querySelector("input");
			inp.addEventListener("input",debounce(500,() => {
				console.log(inp.value);
			}))
			
			
			/*
				delay : 为几秒后 要执行的函数
				fn : 为执行的代码
			*/
			function debounce(delay, fn) {
				let t = null;
				return function() {
					if (t != null) {
						clearTimeout(t);
					}
					console.log("第一次先执行这里");
					t = setTimeout(fn, delay);
				}
			}
			
			
			/*
				当你一直输入,开始执行函数,打印console.log("第一次先执行这里");
				然后定时器 t 赋值为一个数字 赋值完之后并不会立即去执行fn函数
				因为你一直在输入内容,t 一直在赋值,此时就会一直清除定时器
				然后你输入完了,等待500后就会打印 console.log(inp.value);
			
			*/
			
		 </script>

Guess you like

Origin blog.csdn.net/rb0518/article/details/122229595