0

What is the difference between this function:

function printTime(){
        var now = new Date();
        var hours = now.getHours();
        var minutes = now.getMinutes();
        var seconds = now.getSeconds();
        document.write(hours+":"+minutes+":"+seconds+"<br />");
    }
    setInterval('printTime()', 1000);

And this function:

function test(){
        document.getElementById("date").innerHTML = Date();
    }
    setInterval('test()', 1000);

Which prevents "printTime" from actively writing to the page (rather than only firing once), while "test" is capable of functioning as it should?

From all of my experimenting, I've found it to only work when the previous installment was removed or updated (i.e. innerHTML). Is this the case, or am I doing something wrong?

CloudTwoNJ
  • 65
  • 2
  • 8
  • Your problem is the asynchronous use of `document.write`. Don't do that. – Bergi Nov 18 '14 at 23:31
  • Do not use `document.write` when page is loaded! Read this - http://stackoverflow.com/questions/10873942/document-write-clears-page – Cheery Nov 18 '14 at 23:31
  • You should arguably avoid `setInterval` as well, it is possible for calls to stack up if the function doesn't finish before the next invocation. You can use `setTimout(printTime, 1000);` and the last thing the function does is call `setTimeout` with itself. – Jared Smith Nov 18 '14 at 23:44
  • @JaredSmith - There's no issue with using `setInterval()` in a case like this. This is a perfect use case for `setInterval()`. – jfriend00 Nov 19 '14 at 00:11
  • I realize that, but `setInterval` has that problem in general and I said that one should 'arguably avoid' using it, even in cases where it won't cause problems (few js functions take 1000ms to run) just as a good habit. – Jared Smith Nov 19 '14 at 00:19
  • Also, upon further research, it seems that this occurs within Firefox and Internet explorer, but not Google Chrome or Safari. – CloudTwoNJ Nov 19 '14 at 01:06

1 Answers1

0

When called after the page has initially finished loading, document.write() clears the current document and creates a new blank, empty document. Thus, you cannot use document.write() in a recurring interval timer to update your page because it will be continually creating a new empty document.

Instead, you will need to modify the existing DOM by adding new elements, removing elements or changing the contents of existing DOM elements.

For example, you could do this.

HTML:

<div id="currentTime"></div>

Code:

function printTime(){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    document.getElementById("currentTime").innerHTML = hours + ":" + minutes + ":" + seconds;
}
setInterval(printTime, 1000);

This code will regularly update the currentTime div with the current time and will not interfere with other code you may want to run on that page.

jfriend00
  • 683,504
  • 96
  • 985
  • 979