Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - Why does this setInterval/document.write code work on Chrome but not on Firefox?

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...