window.removeEventListener移除节流函数

现在项目里需要实现进入地图区域增加鼠标滚动事件同时需要节流函数来限制执行次数,鼠标移除地图之后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()的打印,下面的节流函数无法执行,求求各位大神指点迷津

  demo(){
        console.log('进入了')
        this.demo2throttle = this.throttle(this.demo2,1500);
        window.addEventListener('mousewheel',this.demo2throttle,false)
    },
  demo3(){
      let that=this
      console.log('禁止滚动了1')
      window.removeEventListener('mousewheel',this.demo2throttle);
    },
  demo2(){
      console.log('滚动了')
    },
 

let timer这个变量是一个局部变量,是不是有点问题,定义为全局变量试试。

您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!

速戳参与调研>>>https://t.csdnimg.cn/Kf0y