节流
定义:不管事件的触发频率有多高,只会在设定的时间间隔内执行一次目标函数。
应用场景:监听浏览器滚动条事件,触发随机改变body
背景颜色的函数changeBgc
。不使用节流会导致页面一滚动就疯狂触发changeBgc
函数,页面会不停闪动。运用节流函数throttle
我们设定1秒时间间隔内只能触发一次changeBgc
函数。
js:
//change body backgroundColor randomly
var changeBgc = function(){
let r = Math.floor(Math.random()*255)
let g = Math.floor(Math.random()*255)
let b = Math.floor(Math.random()*255)
document.body.style.backgroundColor = `rgb(${r},${g},${b})`
}
// bind scroll event to listen window scrolling with throttle
window.addEventListener('scroll',throttle(changeBgc,1000))
// window.addEventListener('scroll',throttle2(changeBgc,1000))
// throttle
function throttle (fun,timeInterval) {
let timer
// return a funciton
return function() {
// pass arguments
let context = this
let args = arguments
// if last function has been apply in timeInterval, skip this function
if (timer){
return
}else{
timer = setTimeout(function(){
fun.apply(context,args)
// a function has been apply in timeInterval, we can start next call
timer = null
},timeInterval)
}
}
}
// throttle2: timestamp
function throttle2 (fun,timeInterval) {
let pre = 0
return function (){
// current time at which this funciton will be triggered
let now = + new Date()
// if time exceed timeInterval after last function has been apply, we can start next call
if (now-pre>timeInterval){
fun()
pre = now
}
}
}
防抖
定义: 触发事件后 n 秒后才执行函数,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。
应用场景: 点击按钮发送Ajax请求。不使用防抖可能会导致用户连续点击按钮时,一段时间后多个相应陆续到来,形成抖动,这样连续请求会造成资源浪费。运用防抖函数,如果用户在请求还未发送的时间内再次点击发送按钮,只会执行最后面一次发送回调。
html:
<body>
<button>点我发送Ajax请求</button>
</body>
js:
const btn = document.querySelector('button')
var sendAjax = function(){
console.log('send request...');
}
// bind click event to send request
btn.addEventListener('click',debounce(sendAjax,2000))
//debounce
function debounce(fun,delay) {
let timer
// return a function
return function (){
let context = this
let args = arguments
// clear last function, execute current new function
clearTimeout(timer)
timer = setTimeout(function(){
fun.apply(context,args)
},delay)
}
}