I am new to JavaScript! I am trying to make an extremely naive blocking statement in a JavaScript program. I think JavaScript is single threaded (mostly, except for things like setTimeout), and synchronous within a code block, so I expected that I could block execution of my code with a while loop. I do not want to use setTimeout because I'm not sure it will be reliably precise enough to do what I want.
Let me explain. I have a button with class="playback"
, which should trigger a series of sounds to play. The callback makes an AJAX request, and then hands data to playbackRecording()
. This function accepts a list of objects which have two attributes: key_pressed
(helps determines which sound to play, but is not important for this issue), and time_to_next_key
(how many milliseconds to wait until the next sound is played). actionApp()
is the function that causes the sound to actually get played.
My expectation: The first sound is played. Then a short amount of time passes and the next action happens. Repeat until finished.
What actually happens: An amount of time elapses that equals the sum of time_to_next_key for all keypresses, then all the sounds are played at the end.
function playbackRecording(content) {
var waitTime = 0;
var keypress = content[0];
actionApp(keypress.key_pressed);
for (var i = 1; i < content.length; i++) {
waitTime += keypress.time_to_next_key;
keypress = content[i];
var end = Date.now() + waitTime;
while(Date.now() < end) {}
actionApp(keypress.key_pressed);
}
}
function playbackLinkClicked(evt) {
var urlString = '/fetch_recording/' + this.id;
$.get(urlString, function(data){
if (data.status === 'success') {
playbackRecording(data.content);
} else {
alert('Could not load recording.');
}
});
}
$('.playback').click(playbackLinkClicked);
What I am missing?