ainjii ainjii - 1 year ago 65
Javascript Question

If JavaScript is (mostly) synchronous and single threaded, why does a while loop not block execution of further statements?

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

, which should trigger a series of sounds to play. The callback makes an AJAX request, and then hands data to
. This function accepts a list of objects which have two attributes:
(helps determines which sound to play, but is not important for this issue), and
(how many milliseconds to wait until the next sound is played).
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];

for (var i = 1; i < content.length; i++) {
waitTime += keypress.time_to_next_key;
keypress = content[i];

var end = + waitTime;

while( < end) {}

function playbackLinkClicked(evt) {
var urlString = '/fetch_recording/' +;

$.get(urlString, function(data){
if (data.status === 'success') {
} else {
alert('Could not load recording.');


What I am missing?

Answer Source

Playing the sound is done by asynchronous code (I don't know exactly what actionApp() does, but the behavior you describe is consistent with this, and it's how most interactive code works in Javascript). So when you call actionApp(), it's putting this code on the event queue. It will not actually play anything until Javascript returns to the main event loop.

The while loop is synchronous, so your code doesn't return until all of them are finished. Each time it calls actionApp() it adds another sound to the event queue. Then when it finishes, all the queued actions get executed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download