We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
防抖、节流函数在我们频繁做出某一行为(如用户input框输入或滚动事件)时会经常用到,本篇文章将带你重新认识:
防抖、节流函数
用户input框输入或滚动事件
防抖:行为发生一定时间后触发事件,在这段时间内如果该行为再次发生,则重新等待一定时间后再触发事件
在这段时间内如果该行为再次发生,则重新等待一定时间后再触发
// 防抖 function debounce(fn,time){ let timer = null return function(){ timer && clearTimeout(timer) timer = setTimeout(()=>{ fn.apply(this,arguments) },time) } }
节流:一段时间内如果行为多次发生,只会触发一次事件
一段时间内如果行为多次发生,只会触发一次事件
function throttle(fn,time){ let oldTimestamp = 0 return function(){ const curTimestamp = Date.now() if(curTimestamp - oldTimestamp >= time){ oldTimestamp = curTimestamp fn.apply(this,arguments) } } }
这里有一段demo代码
const op = document.getElementById('demo') op.addEventListener('click',throttle(sayHi,1000)) function sayHi(){ console.log('sayHi',this) } function debounce(fn,time){ let timer = null return function(){ timer && clearTimeout(timer) timer = setTimeout(()=>{ fn.apply(this,arguments) },time) } }
接着我们继续玩下看
为什么需要使用fn.apply fn.apply主要用于帮我们修改函数运行的this指向, 否则this将指向window
setTimeout为什么要使用箭头函数 不使用箭头函数的话,setTimeout内部this将指向window
setTimeout不使用箭头函数如何实现debounce
const self = this fn.apply(self,arguments)
return function(){}
return ()=>{}
The text was updated successfully, but these errors were encountered:
No branches or pull requests
目录
防抖、节流函数
在我们频繁做出某一行为(如用户input框输入或滚动事件
)时会经常用到,本篇文章将带你重新认识:什么是防抖
防抖:行为发生一定时间后触发事件,
在这段时间内如果该行为再次发生,则重新等待一定时间后再触发
事件什么是节流
节流:
一段时间内如果行为多次发生,只会触发一次事件
防抖、节流函数需要注意的细节
这里有一段demo代码
接着我们继续玩下看
为什么需要使用fn.apply
fn.apply主要用于帮我们修改函数运行的this指向, 否则this将指向window
setTimeout为什么要使用箭头函数
不使用箭头函数的话,setTimeout内部this将指向window
setTimeout不使用箭头函数如何实现debounce
return function(){}
!==return ()=>{}
,这里如果return一个箭头函数,内部this指向也将指向windowThe text was updated successfully, but these errors were encountered: