<div class="move-box">宽100高100</div>
<input type="text" class="input">
<script>
let timer = null
let dTimer = null
let click = function(){
throttle(()=>{
console.log('点击ll')
})
}
let input = function(e){
double(()=>{
console.log(e.target.value)
})
}
document.getElementsByClassName('move-box')[0].onclick = click
document.getElementsByClassName('input')[0].oninput = input
// 节流
function throttle(fn,delay = 1500){
if(!timer){
fn()
timer = setTimeout(()=>{
clearTimeout(timer)
timer = null
},delay)
}
}
// 防抖
function double(fn){
if(dTimer){
clearTimeout(dTimer)
}
dTimer = setTimeout(() => {
fn()
clearTimeout(dTimer)
dTimer = null
}, 500);
}
新增一个
const debounce = (fn, wait = 2000,bthis = false) => {
return function(...args) {
const content = this
if(timer){
clearTimeout(timer)
}
let callNow = !timer
timer = setTimeout(() => {
timer = null
}, wait)
if (callNow){
return bthis ? fn.apply(content, args) : fn(...args)
}
}
}