防抖:设定时间内只触发一次事件,则执行函数,如果发生后续触发,则每次触发都重新开始计时。
var input = document.querySelector("#input")
// 防抖函数
function debounce(delay,callback){
let timer
// 应该存储变量timer,timer变量需要一直保存在内存当中,内存泄漏
return function(value){
clearTimeout(timer)
timer = setTimeout(function(){
// 如果不在这里输出该怎么写?借助回调函数
callback(value)
},delay)
}
}
// 输出结果在这里输出
function fn(value){
console.log(value);
}
var debounceFun = debounce(1000,fn)
input.addEventListener("keyup",function(e){
debounceFun(e.target.value)
})
节流:持续触发事件,一段时间内只调用一次函数。
function throttle(func,wait){
// 点击多少次就会执行多少次,并非我们想要的结果
let timerOut
// 如果timerout不存在则执行一次
return function(){
if(!timerOut){
timerOut=setTimeout(function(){
func()
// 一次执行完后设置timerOut供下次执行
timerOut = null
},wait)
}
}
}
function random(){
console.log(Math.random());
}
document.querySelector("#button").οnclick=throttle(random,2000)