现在项目里需要实现进入地图区域增加鼠标滚动事件同时需要节流函数来限制执行次数,鼠标移除地图之后remove鼠标滚动事件
上代码
throttle(func,delay){
let timer
return function (){
let context =this
let args = arguments
if (timer){
return
}
timer = setTimeout(function (){
func.apply(context,args)
timer = null
},delay)
}
},
demo(){
console.log('进入了')
window.addEventListener('mousewheel',this.throttle(this.demo2,1500),false)
},
demo3(){
let that=this
console.log('禁止滚动了1')
window.removeEventListener('mousewheel',this.throttle(this.demo2,1500));
},
demo2(){
console.log('滚动了')
},
这样就能触发节流函数,但是移除地图区域后,不能顺利的执行
window.removeEventListener('mousewheel',this.throttle(this.demo2,1500));
查了资料后,发现可能是前后执行的函数不一致,后改代码为如下
throttle(func,delay){
let timer
return function (){
let context =this
let args = arguments
if (timer){
return
}
timer = setTimeout(function (){
func.apply(context,args)
timer = null
},delay)
}
},
demo(){
// if (this.doit){//目前这个判断还是需要的,要解决触发
console.log('进入了')
window.addEventListener('mousewheel',this.demo4,false)//demo不能加()
// }
},
demo2(){
console.log('滚动了')
},
demo3(){
let that=this
console.log('禁止滚动了1')
window.removeEventListener('mousewheel',this.demo4);
},
demo4(){
console.log(12312312312)
this.throttle(this.demo2,1500)
},
这样就只能执行到demo4()的打印,下面的节流函数无法执行,求求各位大神指点迷津