1甘晤、
// 防抖:用戶觸發(fā)事件過(guò)于頻繁零截,只要最后一次事件的操作
// 防抖:是只執(zhí)行最后一次
// 節(jié)流的作用:控制高頻時(shí)間執(zhí)行次數(shù)
// 節(jié)流:控制執(zhí)行次數(shù)
2岖瑰、防抖:
let txt = document.querySelector("input")
let time = null
txt.oninput = function(){
if(time !== null){
clearTimeout(time)
}
time = setTimeout(()=>{
console.log(this.value)
},500)
}
封裝寫(xiě)法:
let txt = document.querySelector("input")
txt.oninput = debounce(function() {
console.log(this.value)
}, 500)
// 閉包杀怠,內(nèi)部函數(shù)沒(méi)有執(zhí)行完成排龄,外部函數(shù)變量不會(huì)被銷(xiāo)毀阀坏。
// 應(yīng)用:封裝一段代碼
function debounce(fn, delay) {
let time = null
return function() {
if (time !== null) {
clearTimeout(t)
}
t = setTimeout(() => {
// 利用call來(lái)改變this指向
fn.call(this)
}, delay)
}
}
image.png
3如暖、節(jié)流:
<style>
body{height: 2000px}
</style>
let flag = true
window.onscroll=function(){
if(flag){
setTimeout(()=>{
console.log("123")
flag = true
},500)
}
flag = false
}
封裝寫(xiě)法:
window.onscroll = throttle(function(){
console.log("123")
},500)
function throttle(fn,delay){
let flag = true;
return function(){
if(flag){
setTimeout(()=>{
// fn()
fn.call(this)
flag = true
},delay)
}
flag = false
}
}
4、完成忌堂。