user5490797
user5490797

Reputation:

Why doesn't the document get modified until it's out of the loop?

while (prompt() !== "quit") {
    document.write("test ");
}

I'm expecting this JavaScript to modify the page behind the dialog each time I write something that's not quit.

However it doesn't do so until I do type quit. (Then I see a bunch of tests.) What am I exactly missing?

Upvotes: 1

Views: 60

Answers (4)

Blag
Blag

Reputation: 5894

The refresh of the view behind your alert box seem browser related.

Some will update it between two alert box (as my Firefox on Ubuntu), but your may wait the closing of your alert box before generating the new frame view.

Upvotes: 0

Shomz
Shomz

Reputation: 37701

Because the way prompt works - it blocks everything else on the page before you close it. And since you're calling it in your condition statement, it has to be evaluated before the code decides whether it goes inside the loop or not. It cannot predict whether you'll type "quit" or not. that's why it waits for your input first.


From: https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt

Dialog boxes are modal windows; they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window).

Upvotes: 0

brso05
brso05

Reputation: 13222

It won't execute the loop body until you have typed something into the prompt and clicked enter:

while (prompt() !== "quit") {
    document.write("test "); //waiting for prompt()
}

Upvotes: 0

shafeen
shafeen

Reputation: 2457

The javascript while loop will check the condition (prompt() !== "quit") before running document.write("test "); that is why you aren't seeing the document modified.

Upvotes: 0

Related Questions