防抖与节流及其区别

非商用,仅是自己没事干结合网上百度的封装玩,也没怎么写过博客论坛,如有侵权,留言会删,谢谢
通过在jquery基础上开发

(function(W, $) {

//插件
$.fn.extend({
	xx: function() {
		console.log(1)
	}
});
//方法
W.common = {
	//防抖 n秒内高频率事件触发只执行一次 每次点击重新计时 例:delay=1000;在连续点击时,不管点击多少次,在你停止点击 等待1秒后执行一次,再次连续点击(间断性) delay默认值1000
	debounce: function(fn, delay) {
		var timer = null;
		delay=delay || 1000;
		return function(e) {
			clearTimeout(timer);
			timer = setTimeout(() => {
				fn.apply(this, arguments)
			}, delay)
		}
	},
	//节流 n秒内高频率事件触发执行一次(延迟执行),n秒后的点击会再次触发 例:delay=1;在连续点击时,(不停止)每次点击延迟一秒执行,(持续性) delay默认值1000
	throttle: function(fn, delay) {
		var canRun = true;
		delay=delay || 1000;
		return function() {
			if(!canRun) return;
			canRun = false;
			setTimeout(() => {
				fn.apply(this, arguments);
				canRun = true;
			}, delay)
		}
	}
}

})(window, jQuery)
common.js

你自己的js部分
$(function(){

//document.addEventListener("click",common.debounce(guan,1000))
$("#addList").on("click",common.debounce(debounce,600));
$("#addList").on("click",common.throttle(throttle,600));
//$("#addList").xx();
function debounce(){
	console.log("防抖:",Math.random())
}
function throttle(){
	console.log("节流:",Math.random())
}

})

test.js
先引入jq任意版本,在引入common.js,最后引入你自己的js,此博客引入的为test.js

<button id="addList">测试</button>

test.html

测试结果

测试结果如上图↑↑↑

本人头脑简单,语言组织能力差,所以有些注释可能说的绕口或者很难理解,甚至也存在错误,敬请谅解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值