Promt/Confirm windows appear first, then console.log statements


#1

My code works fine, but I am prompted by my browser for all the input first and then then my console.log statements appear in the console. Is that by design? Shouldn't I confirm or prompt, and then have just the next portion of the story text appear?



#2

JS dialogs (alert(), confirm(), prompt()) are interstitial objects that take precedence in the process queue. Everything else is put to sleep until after this queue is empty. All logging is suspended until then. There is no way to work around a dialog.


#3

Wow, that's a new term for my vocab list. Interesting. Thanks mtf!


#4

When working with dialogs some things to keep in mind may include:

  1. Make sure to null variables typically used in dialogs.
  2. Wrap dialogs in conditional statements so they are out of the normal flow.
  3. Cache repeated strings.

Often we will have a number of dialogs that use a single variable:

user = prompt(" ... ");

If the variable is reused, it will be overwritten. But what if it is tested in the meantime and currently holds its last state? That could generate a false positive in a conditional.

We prevent this by copying the value to another variable and set this one to null.

choice = user;
user = null;

By wrapping dialogs in conditional statements we can limit the number of them in the current process queue (my term, by the way, bears reading) at any one time and give our output a chance to display when normal flow is resumed. This is by no means a slam dunk approach, and only comes up intuitively, here. It will bear much testing to prove it out.

The last point about caching repeated strings is just a way to make code more D.R.Y. and easier to read. The logic in each instance may be different, but hidden by the repeated strings. Caching the strings places them out of view so we can see the logic in each instance.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.