How can I delay submit

How can I delay submit until the audio file finished because when submit event-triggered the page refreshed without playing the sound file I’ve tried this but it’s not working.

<form action="/game1/" method="POST" onsubmit="checkAnswer()">
        {% csrf_token %}
        <input type="hidden" name="UserSorce" id="us" >
        <button type="submit" class="btn btn-primary btn-circle btn-xl">
          Check
        </button>
      </form>
function checkAnswer()
  {
    let tmp=document.getElementById("answer").innerText;
    if(correctAns==tmp)
    { 
        document.getElementById("result").src=picCorrect;
        document.getElementById("result").style.display="block";
        var audio = new Audio(soundCorrect);
        audio.play();
        audio.onended = function () {
          return true;
        }
    }else{
        document.getElementById("result").src=picIncorrect;
        document.getElementById("result").style.display="block";
        var audio = new Audio(soundIncorrect);
        audio.play();  
    }
  }

Answer

You almost have all the stuff in place you need. The trick here is don’t trigger the submission using the form’s submit button. Instead add a simple html button, which calls checkAnswer().

Inside the checkAnswer() function you are already listening for the audio’s onended event. If that happened you can finally submit the form using it’s submit() function.

A little something like this:

<form id="myForm" action="/game1/" method="POST">
  <input type="hidden" name="UserSorce" id="us">
</form>
<button onclick="checkAnswer()">
  Check
</button>

and

function checkAnswer() {
  let tmp = document.getElementById("answer").innerText;
  if (correctAns == tmp) {
    document.getElementById("result").src = picCorrect;
    document.getElementById("result").style.display = "block";
    var audio = new Audio(soundCorrect);
    audio.onended = function() {
      document.getElementById("myForm").submit();
    }
    audio.play();

  } else {
    document.getElementById("result").src = picIncorrect;
    document.getElementById("result").style.display = "block";
    var audio = new Audio(soundIncorrect);
    audio.play();
  }
}