Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

The document.write doesnt execute until the end I assume?

I initially wanted to give feedback for the score after each question. The document.write was not executing until after all the questions were answered. I assume thats normal and there is probably a better way to do that once I learn a little more? The code below worked great for one question. After I added a second is where I noticed the document.write not executing until all questions had been answered. It seemed to run all of them at the end, even though I had it in each question.

var totalCorrect = 0
var Q1 = prompt('What year was the USMC founded?');
if (parseInt(Q1) === 1775 ){
  totalCorrect += 1
document.write('<p>Correct! ' + 'You have answered ' + totalCorrect + ' correct so far</p>');
} else {
document.write('<p>Sorry. ' +  Q1 + ' was not correct.' +  'You have answered ' + totalCorrect + ' correct so far</p>');
}

Edited by Dane E. Parchment Jr. - moderator

1 Answer

Steven Parker
Steven Parker
229,644 Points

I think the function actually does execute right away, but the rendering of the page is delayed until the script ends. Either way, it makes it unusable for immediate feedback during execution. But for an immediate display you can use "alert".

As you progress in your studies, you'll soon learn about event handlers and input controls which will give you much better tools for making your pages interactive.