【问题标题】:Disable function when other function is running在其他功能运行时禁用该功能
【发布时间】:2021-12-05 15:47:13
【问题描述】:

我有两个事件侦听器,它们都会根据视频状态在页面加载时触发。但如果两者都被解雇,我希望第一个停止运行。这怎么可能?

obj.addEventListener('suspend', () => {
  // when only this is fired -> run this code
  
  // my code
});

obj.addEventListener('play', () => {
  // when this is fired too -> run this code and deactivate the first code
  
  // my code
});

【问题讨论】:

    标签: javascript function addeventlistener


    【解决方案1】:

    您需要定义一个全局变量并检查它是否为 true ,而不是触发第一个函数。 但是可能存在一些运行时问题,如果在运行第一个事件,调用第二个事件之间,第一个事件不会冻结并继续运行。

    let shouldRun = true;
    obj.addEventListener('suspend', () => {
      // when only this is fired -> run this code
    
    if(!shouldRun){
      return;
    }
    // my code
    });
    
    obj.addEventListener('play', () => {
      // when this is fired too -> run this code and deactivate the first code
      shouldRun = false;
      // my code
    });
    

    【讨论】:

    • 谢谢,但不幸的是,这两个功能仍在运行..
    • 你能明确一下这些活动什么时候来吗?在同一时间或第一次play 电话,然后suspend 或其他一些订单?
    • 每次先调用suspend事件,再调用play事件..
    【解决方案2】:

    我猜你可以尝试在 Call of 'play' 事件中使用 obj.removeEventListener('suspend')。

    关于 removeEventListener 的更多信息,你可以通过官方链接。 https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener

    【讨论】:

    • 谢谢,看起来是个不错的解决方案,但我收到“参数不足”错误。你知道我要在这里添加什么吗?
    【解决方案3】:

    解决此问题的一种简单方法是使用removeEventListener() 删除事件处理程序。

    function handleSuspend() {
      // when only this is fired -> run this code
      
      // my code
    }
    
    function handlePlay() {
      // when this is fired too -> run this code and deactivate the first code
      obj.removeEventListener('suspend', handleSuspend);
      
      // my code
    }
    
    obj.addEventListener('suspend', handleSuspend);
    obj.addEventListener('play', handlePlay);
    

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 2021-06-26
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多