I am working on an HTML page which plays music scores online. I have an issue with JavaScript. Especialy when i try to implement a time range between the musical notes which are played.
Here is my HTML code :
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<audio id="note1" src="Mbira1.mp3"></audio>
<audio id="note2" src="Mbira3.mp3"></audio>
<audio id="note3" src="Mbira5.mp3"></audio>
<button onclick="test()">Test</button>
</body>
</html>
And here is my JavaScript code :
function test(){
let note1 = document.querySelector("#note1");
let note2 = document.querySelector("#note2");
let note3 = document.querySelector("#note3");
let timeSave = Date.now();
let timeNow = null;
while(timeNow - timeSave < 2000){
if (timeNow == null) {
console.log("Begin");
note1.play();
}
timeNow = Date.now();
}
console.log("End");
}
When the "test()" function is executed, no matter if "note1.play();" is placed before the "while" loop or inside it, the sound always comes out after the loop. I'm not sure but it could be because JavaScript is an asynchronous programing language,like it executes the loop first and then the "note1.play()" instruction. I don't know how can I solve this issue. I don't want it to play every notes at the same time. I wish it could play the notes' duration correctly.