1. 程式人生 > 實用技巧 >JS防抖和節流

JS防抖和節流

JS防抖和節流

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<style>
		#content{
			width: 500px;height: 150px;
			background-color: beige;
			color: #484848;
			text-align: center;
			font-size: 60px;
			font-weight: 600;
			line-height: 150px;
		}
	</style>
	<body>
		<input id="search" type="text" oninput="count()"/>
		<div id="content"></div>
		<script>
			let num = 1;
			let content = document.getElementById("content");
			function count(){
				content.innerHTML=num++;
			}
                        //觸發完畢過兩秒執行,重新觸發,時間重新計算
			function debounce(func,wait){
				let timeout;
				return function(){
					if(timeout) {
						clearTimeout(timeout)
					}
					timeout = setTimeout(function(){
						func.apply(this);
					},wait)					
				}
			}
			content.onmousemove = debounce(count,2000);
			// content.onmousemove = count;
		</script>
	</body>
</html>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<style>
		#content{
			width: 500px;height: 150px;
			background-color: beige;
			color: #484848;
			text-align: center;
			font-size: 60px;
			font-weight: 600;
			line-height: 150px;
		}
	</style>
	<body>
		<input id="search" type="text" oninput="count()"/>
		<div id="content"></div>
		<script>
			let num = 1;
			let content = document.getElementById("content");
			function count(){
				content.innerHTML=num++;
			}
			//觸發完畢立即執行,過2秒才能再次執行
			function debounce(func,wait){
				let timeout;
				return function(){				
					if(timeout) clearTimeout(timeout)				
					let callNow = !timeout; 
					//型別轉換,第一次執行timeout,callNow為turn
					timeout = setTimeout(function(){
						timeout = null;//清空當前定時器控制代碼
					},wait)	
					if(callNow) func.apply(this);//第一次執行
				}
			}
			content.onmousemove = debounce(count,2000);
			// content.onmousemove = count;
		</script>
	</body>
</html>