So, I was reading an article on MSDN here concerning the many ways one can display text to a webpage using JavaScript. However, I found the last example quite confusing as the behavior of the example as described in the article and exhibited in IE11 does not match the behavior shown in Chrome.
Here is the example:
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="[StackOverlow document.write() question]">
<script type="text/javascript">
function ShowTime()
{
var dt = new Date();
document.write(dt.toTimeString());
// var elem = document.getElementById("divElem");
// elem.textContent = dt.toTimeString();
window.setTimeout("ShowTime();", 5000);
}
</script>
</head>
<body>
<script type="text/javascript">
ShowTime();
</script>
<div id="myDiv"></div>
</body>
</html>
The code is described as displaying the time only twice with a 5 second interval in between. This is correct for IE11. To be explicit, this is what is happening:
- The time is immediately displayed
- Wait 5 seconds
- The time displayed is updated to the current time
However, if I run the example in Chrome, it runs as follows:
- The time is immediately displayed
- Wait 5 seconds
- The time displayed is updated to the current time
- Wait 5 seconds
- A separate timestamp is displayed beside what is already displayed
- Repeat steps 4 and 5 indefinitely...
Can anyone please elaborate as to why the code behaves the way it does by explaining the mechanics behind using document.write() and setTimeout() for each browser?
Any help is much appreciated. Thank you in advance!