js anti-shake function throttling function

In some events (such as onresize onscroll onkeydown onkeyup onmousemove ...), the execution of the function will be triggered continuously. If the function performs some time-consuming operations (such as requesting data...), it will affect performance and may cause server pressure. At this time, the anti-shake function or throttling function can be used to solve this problem.

Anti-shake function:

No matter how the event is connected to trigger the execution of the function, I only execute the function once N milliseconds after the event ends; if the event is still connected to trigger, the function will not be executed.

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8" />
	<style type="text/css">
		#box{
      
      width:200px;height:200px;border: 1px solid red;}
	</style>
</head>
<body>

<div id="box"></div>

</body>
<script>
function debounce(fn,wait){
      
      
  let timeoutId = null;
  return function(){
      
      
  	let args = arguments;
    timeoutId && clearTimeout(timeoutId);
    timeoutId = setTimeout(function(){
      
      
      fn(args);
    },wait)
  }
}
function doing(arg){
      
      
	console.log(arg);
}
let fn = debounce(doing,1000);
box = document.getElementById("box");
box.onmousemove = function(){
      
      
	fn(1,2,3);
}
</script>
</html>

Renderings:

Please add a picture description


Throttle function:

When the event is triggered by the connection, I will execute the function every N milliseconds; if the event is triggered multiple times within N milliseconds, the function will only be executed once.

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<meta charset="utf-8" />
	<style type="text/css">
		#box{
      
      width:200px;height:200px;border: 1px solid red;}
	</style>
</head>
<body>

<div id="box"></div>

</body>
<script>
function throttle(fn,wait){
      
      
	let timeoutId = null;
	return function(){
      
      
		let args = arguments;
		let now = Date.now();
		if(!timeoutId){
      
      
			timeoutId = setTimeout(function(){
      
      
				timeoutId = null;
				fn(args);
			},wait)
		}
	}
}

function doing(arg){
      
      
	console.log(arg);
}
let fn = throttle(doing,1000);
box = document.getElementById("box");
box.onmousemove=function(){
      
      
	fn(1,2,3);
}
</script>
</html>

Renderings:

Please add a picture description

Experience the difference between the anti-shake function and the throttling function by yourself.
You can experience it according to the effect diagram.
If you don’t understand the experience, write it yourself and try it out.

Application scenarios of the anti-shake function: Baidu is recommended. too lazy to write.
The application scenario of the throttling function: Baidu is recommended. too lazy to write.

----END----
Learning only.

Guess you like

Origin blog.csdn.net/qq_52722885/article/details/129110841