#什么是防抖和节流?有什么区别?如何实现?
防抖可加入第三个参数用于判断实现中,需要第9行代码吗?这样不会导致callNow一直为true吗?
第二次再触发,如果定时器还没走完,这时候已经有上一次的timeId了,区反就是false了,所以就不会进入到函数执行了。当定时器到了把timeId设置为null了,这时候又可以立即执行函数,以此类推....
我们刚才讨论的好像还是有些问题,2s内连续触发,防抖预期应该只执行最后一次的。也不能单独通过判断timer直接执行,应该是下面这样子实现就可以 function debunce(fn,delay){ let timer let context = this return function(){ if(timer){ clearTimeout(timer) } timer=setTimeout(()=>{ fn.apply(context,arguments) timer=null },delay) } }
------------------ 原始邮件 ------------------ 发件人: "febobo/web-interview" @.>; 发送时间: 2023年6月12日(星期一) 晚上9:36 @.>; @.@.>; 主题: Re: [febobo/web-interview] #什么是防抖和节流?有什么区别?如何实现? (Issue #390)
第二次再触发,如果定时器还没走完,这时候已经有上一次的timeId了,区反就是false了,所以就不会进入到函数执行了。当定时器到了把timeId设置为null了,这时候又可以立即执行函数,以此类推....
— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you authored the thread.Message ID: @.***>
这样没有立即触发的效果,只能是定时器走完了没有重新触发事件才触发的
今天又看了下,我之前那个触发有延时的问题的。立即执行看网上是有新增的变量辅助判断,但是我感觉下面的应该就可以了 function immediateDebunce(fn,delay){ let timer let context = this return function(){ if(!timer){ //首次满足条件直接调用 fn.apply(context,arguments) } timer && clearTimeout(timer) //频繁点击不加此步骤会产生很多定时器,故需要先清除再设置 timer=setTimeout(()=>{ //首次触发delay时间段继续点击,通过设置timer timer=null },delay) } }
------------------ 原始邮件 ------------------ 发件人: @.>; 发送时间: 2023年6月13日(星期二) 晚上11:23 收件人: @.>; 抄送: @.>; @.>; 主题: Re: [febobo/web-interview] #什么是防抖和节流?有什么区别?如何实现? (Issue #390)
这样没有立即触发的效果,只能是定时器走完了没有重新触发事件才触发的
— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you authored the thread.Message ID: @.***>
是的,看了一下逻辑好像也是没问题的