封装防抖节流函数、事件对象event对象的存活期

在封装防抖函数时,在网站上借鉴了下其它答主的办法,发现大家都是这样封装的:

function debounce(method,delay){
let myTimer=null;
return function(){
myTimer && clearTimeout(myTimer);
let self=this;
args = arguments;
var myTimer=setTimeout(function(){
   method.apply(self,args)
},delay)
}
}
//示例:
window.onclick=debounce(function(){
   console.log("点监听执行")
},1000)

这样写确实没有问题,但是当我们想使用事件对象的时候,会发现根本用不了,打印event 会是undefinded
在这里插入图片描述
所以这是为什么?
因为event是有存活期的,一旦过了存活期,便再访问不到,事件结束,事件对象被回收,而在防抖函数中我们使用了延时调用器,在里面我们是访问不到event的,但是我们要用,所以在延时调用器外面先把event存起来

这是我认为比较完美的防抖函数封装:

function debounce(method,delay){
	let myTimer=null;
	return function(){
	myTimer&&clearTimeout(myTimer)
	let self=this;
	var event=self.event  //此时event对象还存在与self指针中
	self.event=event//这条语句的作用是将event对象保存下来,不被清除
	args=arguments;
	var myTimer=setTimeout(function(){
	method.apply(self,args)
	},delay)
	}
}

window.onclick=debounce(function(){
console.log(event)
},1000)

打印结果:
在这里插入图片描述
现在就可以在method函数中使用事件对象了

节流函数封装:

function throttle(method,delay){
			let lastime,start
			return function(){
				let self=this;
				let args=arguments;
				event=self.event;
				self.event=event;
				if(!start){
					method.apply(self,args)
					start=true;
					lastime=Date.now()
				}
				else{
					if(Date.now()-lastime>=delay){
						method.apply(self,args);
						lastime=Date.now()
					}
				}
			}
		}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
TypeScript(简称TS)是一种由微软开发的开源编程语言,它是JavaScript的一个超集,可以编译成纯JavaScript代码。在TS中,我们可以使用装饰器和泛型等特性来封装防抖节流函数防抖函数节流函数都是用于控制函数执行频率的方法,常用于优化性能和避免重复触发事件防抖函数的作用是在一定时间内,如果事件持续触发,则重新计时,直到事件停止触发后才执行函数。常见的应用场景是输入框搜索联想功能。 节流函数的作用是在一定时间内,无论事件触发多少次,只执行一次函数。常见的应用场景是滚动加载数据。 下面是一个使用TS封装防抖节流函数的示例: ```typescript // 防抖函数 function debounce(func: Function, delay: number): Function { let timer: number | null = null; return function (...args: any[]) { if (timer) { clearTimeout(timer); } timer = setTimeout(() => { func.apply(this, args); }, delay); }; } // 节流函数 function throttle(func: Function, delay: number): Function { let timer: number | null = null; return function (...args: any[]) { if (!timer) { timer = setTimeout(() => { func.apply(this, args); timer = null; }, delay); } }; } ``` 使用示例: ```typescript function search(keyword: string) { // 模拟搜索功能 console.log(`Searching for ${keyword}`); } const debouncedSearch = debounce(search, 300); const throttledSearch = throttle(search, 300); debouncedSearch('apple'); debouncedSearch('banana'); debouncedSearch('cherry'); throttledSearch('apple'); throttledSearch('banana'); throttledSearch('cherry'); ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值