防抖
作用:在多次触发事件的情况下,只执行一次
第一版
var debounce = function(func){
let timer;
return function(){
if(timer){clearTimeout(timer)}
timer = setTimeout(() => {
// func()
console.log(this)
func.apply(this)
},1000)
}
}
var fun1 = function(){
console.log(this)
}
var debounceTask = debounce(fun1)
var input = document.getElementById('input')
input.addEventListener('keydown',debounceTask)
思路
首先定义一个变量 用于接收创建定时器的id,方便清除定时器
在设置定时器前,先判断是否之前创建的定时器存在,如果存在就清除
问题
没有绑定this
没有使用apply之前,this默认指向window
使用apply之后,this就会指向函数执行的环境
第二版
var debounce = function(func,wait){
let timer;
return function(...args){
if(timer){clearTimeout(timer)}
timer = setTimeout(() => {
func.apply(this,args)
},wait)
}
}
优化
两种情况:
1.用户在搜索问题时连续输入内容,在输入最后一个字符时执行函数,函数执行时间间隔小于指定的时间。
2.用户在star时,需要第一时间看到反馈,此函数需要立即执行,反馈情况给用户看,下一次调用时间间隔必须大于wait才会触发
var button = document.getElementById('button');
var start = document.getElementById('star')
var divstatue = function(){
if(start.style.background == 'red'){
start.style.background = 'blue';
console.log(this)
}else{
start.style.background = 'red';
console.log(this)
}
}
var debounce2 = function(func,wait){
var context,arg;
var timer
var later = function(){
timer = setTimeout(() => {
timer = null
func.apply(context,timer)
}, wait);
}
return function(...args){
context = this
arg = args;
if(!timer){
func.apply(context,arg)
}else{
later()
}
}
}
var debounceTask2 = deboncetest3(divstatue,1000)
button.addEventListener('click',debounceTask2)