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 trialHarish Yerra
10,031 PointsBoth alerts are appearing before the h1 text is shown
So this is my code:
alert("Hello from Treehouse");
document.write("<h1>Welcome to Javascript Basics!<h1>");
alert("Thanks for visiting!");
However, once the webpage loads the order of events is as follows:
- alert("Hello from Treehouse");
- alert("Thanks for visiting!");
- document.write("<h1>Welcome to Javascript Basics!<h1>");
However, the teacher says that the program executes in order after each action is completed. So shouldn't it appear in this order:
- alert("Hello from Treehouse");
- document.write("<h1>Welcome to Javascript Basics!<h1>");
- alert("Thanks for visiting!");
1 Answer
Steven Parker
231,269 PointsNothing written to the document will appear until the JavaScript finishes.
So while the document.write is performed between the alerts, it will not be seen until after the last alert is closed.
Here's a trick you can use to cause the page to appear at the same time as the last alert (and not wait on it closing):
alert("Hello from Treehouse");
document.write("<h1>Welcome to Javascript Basics!<h1>");
setTimeout(function() { alert("Thanks for visiting!"); }, 0);
Harish Yerra
10,031 PointsHarish Yerra
10,031 PointsAhhhh...
That makes sense! Thanks for clarifying :)
Steven Parker
231,269 PointsSteven Parker
231,269 PointsI updated my answer with a trick you may find useful.
Harish Yerra
10,031 PointsHarish Yerra
10,031 PointsCool :)
Thanks for helping me out! So basically, the code above creates a little timeout between the document.write and the alert so that the page updates and then displays an alert.
Is that basically what it does or is the reasoning behind it different?