js 防抖

本文详细介绍了JavaScript中的防抖(debounce)函数实现原理及其应用。通过两个按钮的点击事件,展示了如何使用防抖函数来避免在短时间内连续触发多次事件处理,从而提高网页性能和用户体验。文章提供了完整的HTML和JavaScript代码示例。
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<button onclick="aclick()">抖动测试1</button>
	<button onclick="bclick()">抖动测试2</button>
	<script>
	
		var b1 = function(){
			console.log("bbb");
		}
		var a1 = function(){
			console.log("aaa");
		}
		var a = debounce(a1,2000)
		var b = debounce(b1,2000)
		function debounce(fn, wait) {
    		var timeout = null;
 
    		var debounced = function() {
	        	// 用that保存dom2级事件处理中绑定的元素对象
	        	// arg保存默认传给事件处理程序的参数
	    		var that = this,
	    			arg = arguments;
	    		var callNow = !timeout;
	 
	        	if (timeout) clearTimeout(timeout);
	        	timeout = setTimeout(function(){
	        		timeout = null
	        	}, wait)
	        	if(callNow){
	        		fn.apply(that,arg);            
	        	};
    		}
    		return debounced;
		}
		function aclick(){
			a();
		}
		function bclick(){
			b();
		}
	</script>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值