为什么setInterval / document.write代码可以在Chrome上运行,但不能在Firefox上运行? [英] Why does this setInterval/document.write code work on Chrome but not on Firefox?

查看:331
本文介绍了为什么setInterval / document.write代码可以在Chrome上运行,但不能在Firefox上运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



var t = 1; var a = (){if(t <11){document.write(t +< br />>); t = t + 1; } else {clearInterval(handle); }} var handle = setInterval(a,100);


$ b

在Chrome上工作(数字1到10之间出现短暂的延迟),但不适用于Firefox(只出现1,没有错误)。为什么?

我知道我可以使用 console.log ,但那不是重点。为什么 document.write 在Chrome和Firefox之间以不同的方式工作?

解决方案

这是 Chrome WebKit中的一个错误;根据 Kaiido ,它也发生在Safari。



调用 document.write 在对页面的主解析完成之后涉及对 document.open 根据规范,调用 document.open 应该销毁文档,删除所有的事件处理程序,并放弃所有的任务。这意味着Firefox正在做的是正确的,因为它在空白文档中显示1。它不会继续执行,因为 setInterval 计划的任务已经被丢弃。



,有时Firefox的微调继续前进,就像期待其他事情发生。我喜欢 Adam Konieska的理论原因是:当我们做了 document.write(1)时,我们隐式做了一个 document.open ,它正在等待 document.close 。实际上,如果我们在你的代码中添加一个 document.close 来测试它,那么这个微调不会停留在这个地方:


$ b $如果您的数据库中包含一个或多个数据库,那么您可以使用这些数据库中的数据库来创建数据库:

var t = 1; var a = function timer(){if(t <11){ document.write(t +< br />); t = t + 1; document.close(); //只是测试Firefox的微调} else {clearInterval(handle);

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

这篇关于为什么setInterval / document.write代码可以在Chrome上运行,但不能在Firefox上运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆