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?
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.
Wow, that's a new term for my vocab list. Interesting. Thanks mtf!
When working with dialogs some things to keep in mind may include:
- Make sure to null variables typically used in dialogs.
- Wrap dialogs in conditional statements so they are out of the normal flow.
- 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
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.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.