Here is a simple program that prints numbers one to ten on the browser window.
var t = 1;
var a = function timer() {
if (t < 11) {
document.write(t + "<br/>");
t = t + 1;
} else {
clearInterval(handle);
}
}
var handle = setInterval(a, 100);
This works on Chrome (the numbers 1 to 10 appear with a brief delay between them) but doesn't work on Firefox (just 1 appears, and no errors). Why?
I understand I could use console.log, but that's not the point. Why is document.write working differently between Chrome and Firefox?
It's a bug in Chrome WebKit; according to Kaiido, it also happens on Safari.
Calling document.write after the main parsing of the page is complete involves an implicit call to document.open. According to the specification, calling document.open should destroy the document, remove all event handlers, and discard all tasks. That means what Firefox is doing is correct, because it shows 1 in a blank document. It doesn't keep going because the task scheduled by the setInterval has been discarded.
As you've noted, sometimes the Firefox spinner keeps going, like it's expecting something else to happen. I like Adam Konieska's theory about why that is: When we did the document.write(1), we implicitly did a document.open, and it's waiting for a document.close. And in fact, if we add a document.close to your code to test that, the spinner doesn't stick around:
var t = 1;
var a = function timer() {
if (t < 11) {
document.write(t + "<br/>");
t = t + 1;
document.close(); // Just to test Firefox's spinner
} else {
clearInterval(handle);
}
}
var handle = setInterval(a, 100);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With