Howdy,
The document.write() function has only one chance to run, and this is whilst the document is being rendered in the browser window.
During the rendering the document is said to be "open", and when the rendering finishes the document "closes". This happens automatically once during initial page loading, but can also be done explicitly at any other time using document.open() and document.close().
When you call the document.write() function while the document is closed, (i.e. in response to an event or something) you are supposed to first open the document with document.open(). This wipes the document clean and allows new content to be written to it.
If you don't use document.open() first, it is called implicitly and executes anyway. Thus, the window is always cleared.
Afterwards, use document.close() to complete the process or else the stuff you wrote may not appear at all.
Usually when you use document.write(), make sure it runs while the page is still loading. (open) Then it should work as expected, and open/close need not be used.
I hope this answers your questions about document.write().
Cheers,
Petey