0

I've got this code in javascript right before a window.prompt() function. However, the code preceding the prompt is obstructed by the prompt, even though it's before the prompt() function. For example, here's what I'm expecting to see:

console.log('Hello World!');
const prompt = window.prompt(message, defaultText);

Hello World!

*PROMPT OPENS*

However, it does this:

console.log('Hello World!');
const prompt = window.prompt('See how the console.log doesn\'t appear while this is open?', 'Yes, I do see that! Clicking Cancel or Ok then logs it!');

What causes this to happen? I'd understand if the console.log came after the prompt rather than before it.

Any assistance would be greatly appreciated. Thank you.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
K.K Designs
  • 688
  • 1
  • 6
  • 22
  • 1
    Just how the browser runs the update cycle. The sleep waiting for the prompt blocks the render of the new content from firing. – epascarello Feb 28 '22 at 20:22
  • But my code is ***BEFORE*** the prompt function; shouldn't it sleep the code after it? – K.K Designs Feb 28 '22 at 20:26
  • Hopefully someone can post a link to a good answer on another question that explains how rendering/screen painting works. – epascarello Feb 28 '22 at 20:31
  • 1
    No. `prompt()` just blocks the execution. [If the browser does the actual output later](https://stackoverflow.com/questions/23392111/console-log-async-or-sync) then it's completely reasonable that you won't see the logs until the thread is unblocked. – VLAZ Feb 28 '22 at 20:34
  • So that means code before and after are blocked, creating the same behavior as if the prompt function was at the top? – K.K Designs Feb 28 '22 at 20:48
  • 1
    No, it does not mean that. It means that *if the code on top* requires some interaction *that needs the current processing to finish*, then that interaction will be blocked. In the snippet here the log is "delayed" because it actually updates the DOM. And the DOM needs the UI thread to refresh. If you check the actual browser console you'd see `"Hello World!"` printed in both Firefox and Chrome even if you don't close the prompt box. Which is not what you see in the snippet, since the snippet uses a different way to show the log to a normal browser. – VLAZ Feb 28 '22 at 21:13
  • Can someone make this an answer so I can mark it as done? – K.K Designs Mar 01 '22 at 00:47

0 Answers0