节流
1.不传参的写法
<button type="button" class="throttleBtn">节流</button>
function throttle(fn,delay){
let timeOut = null
return function(){
if(!timeOut){
timeOut = setTimeout(()=>{
fn()
timeOut = null
},delay)
}
}
}
function notice(value){
console.log('节流执行!',value)
}
$('.throttleBtn').click(throttle(notice,1000))
2.传参的写法
function throttle(fn,delay,args){
let timeOut = null
return function(){
if(!timeOut){
timeOut = setTimeout(()=>{
fn.apply(this, args)
timeOut = null
},delay)
}
}
}
function notice1(value,value1){
console.log('节流执行!',value,value1)
$('.content').append('节流执行!'+value+','+value1)
}
$('.throttleBtn').click(throttle(notice1,1000,[55,33]))
防抖
1.不传参的写法
<button type="button" class="debounceBtn">防抖</button>
function debounce(fn,delay){
let timeOut = null
return function(){
if(timeOut) clearTimeout(timeOut)
timeOut = setTimeout(fn,delay)
}
}
function notice(){
console.log('防抖执行!')
}
$('.debounceBtn').click(debounce(notice,1000))
2.传参的写法
function debounce(fn,delay,args){
let timeOut = null
return function(){
if(timeOut) clearTimeout(timeOut)
console.log('fn',fn,timeOut)
timeOut = setTimeout(()=>{
fn.apply(this, args)
},delay)
}
}
function notice(value){
console.log('防抖执行!',value)
}
$('.debounceBtn').click(debounce(notice,1000,[888]))