Why is my JavaScript function continuing when I have told it to stop while another function runs?

Not sure why this function is continuing to run. Function a() should always be running except when function b() is running. Function b() is initiated when a button with the class ‘btn’ is clicked. I can’t figure out why this isn’t working. Thanks!

    var bActive = false;
    
    if(bActive == false){
        a();
    }
    function a(){
        const toggleGreat = document.querySelector('.great')
        const rawr = document.querySelector('.rawr')

        toggleGreat.addEventListener('mouseover', function(){
        rawr.classList.remove('active');
        })
    }
    function b(){
        bActive = true;

        const rawr = document.querySelector('.rawr');
        const paper = document.querySelector('.paper');

        rawr.classList.add('active');
        paper.classList.remove('active')
    }

    btn.addEventListener('click',function(){
        b();
    }

32 thoughts on “Why is my JavaScript function continuing when I have told it to stop while another function runs?”

  1. Functions don’t "continue to run" the way you describe. Both functions bind event handlers to the DOM and exit immediately. You can’t change the functionality of a after a has already run.

    One possible solution is to test whether bActive is true inside the event handler:

    var bActive = false;
    
    const toggleGreat = document.querySelector('.great')
    const rawr = document.querySelector('.rawr')
    const paper = document.querySelector('.paper');
    
    toggleGreat.addEventListener('mouseover', function(){
      if (!bActive) {
        rawr.classList.remove('active');
      }
    })
    
    btn.addEventListener('click',function(){
      bActive = true;
      rawr.classList.add('active');
      paper.classList.remove('active')
    }
    
    Reply

Leave a Comment