0

I am getting a (what seems to be) random promise error during my switch statement below. I have created a random number, and associated it with a given array items position. I use this position inside my switch statement to play a specific sound. When testing this inside the browser I sometimes get an in promise exception like below:

playSound @ game.js:29
nextSequence @ game.js:18
(anonymous) @ game.js:45

Even though I get this error everything works as intended. EDIT PIECE: When debugging with debugger; the above is present intermittently

//store colors

var buttonColors = [
    "green", //0
    "red", //1
    "yellow", //2
    "blue" //3
]

gamePattern = [ /*Added From nextSequence*/ ]

//Generate a random number
function nextSequence() {
    randomNumber = Math.floor(Math.random() * 4)
    randomChosenColor = buttonColors[randomNumber];
    gamePattern.push(randomChosenColor);
    $(`#` + randomChosenColor).fadeOut(100).fadeIn(100).delay(200);
    playSound(randomChosenColor);
}

function playSound(color) {
    switch (color) {
        case 'green':
            var greenButton = new Audio('sounds/green.mp3');
            greenButton.play();
            break;
        case 'red':
            var redButton = new Audio(`sounds/red.mp3`);
            redButton.play();
            break;
        case `yellow`:
            var yellowButton = new Audio(`sounds/yellow.mp3`);
            yellowButton.play();
            break;
        case `blue`:
            var blueButton = new Audio(`sounds/blue.mp3`);
            blueButton.play();
            break;
        default:
            console.log(`Play Sound Error in playSound Function`)
    }
}


nextSequence();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  • 1
    Maybe [this](https://stackoverflow.com/questions/40276718/how-to-handle-uncaught-in-promise-domexception-the-play-request-was-interru) answers your question. – Ammar May 31 '19 at 16:00
  • Not an answer or in anyway related to the error, but you don't need the `switch`: `function playSound(color) { if (color) { new Audio("sounds\" + color + ".mp3").play(); } }` – Andreas May 31 '19 at 16:08
  • Thanks @Andreas . I have changed it to concatenation without the need for any if or switch statements and just placed it inside a variable. '''var audio = new Audio("sounds/" + randomChosenColour + ".mp3"); audio.play();''' – Colton Van Bastelaere May 31 '19 at 16:30
  • @Ammar This is perfect. It works fine on Mozilla and I really don't want to add any work around code right now, the game will have a play button later anyway. I found this before but I first thought this was only related to video content. Thank you ! – Colton Van Bastelaere May 31 '19 at 16:37

0 Answers0