javascriptaudiopause

Can't stop the audio with Js


I have a problem with Javascript:

I want to stop the audio in a Js program when the game comes to an end. For this I define a variable "endGame" and I make it false, so that when I call it true in an event, the audio stops. But the problem is that the audio does not stop when this variable is set to true.

Here's the piece of code that I need some help with:

let endGame = false

main.addEventListener("click", (e) => {
    themeSong.play() 
    
    if(endGame == true) {
        themeSong.pause()
    }

Solution

  • EventListeners will not be triggered when the variable change. You should do it manually.

    let endGame = false;
    
    main.addEventListener("click", (e) => {
        themeSong.play();
    });
    
    // The function which updates the endGame variable and stop the audio
    function fnEndGame() {
       endGame = true;
       themeSong.pause();
    }
    
    // You should call fnEndGame() to stop the game, DO NOT update the variable directly.