2017-07-16 84 views
0

我用window.open()做了一个空白窗口。
然后我用1秒的延迟添加了一个字符串“Wait a minute ...”3次。
就在添加字符串之前,我登录了窗口的正文。使用“setTimeout()”时的执行顺序是什么?

窗口显示字符串,如我所料,但控制台日志不是。

日志

tmp.html:20 <body>​<h1>​Wait a minute...​</h1>​<h1>​Wait a minute...​</h1>​<h1>​Wait a minute...​</h1>​</body>​ 
tmp.html:20 <body>​<h1>​Wait a minute...​</h1>​<h1>​Wait a minute...​</h1>​<h1>​Wait a minute...​</h1>​</body>​ 
tmp.html:20 <body>​<h1>​Wait a minute...​</h1>​<h1>​Wait a minute...​</h1>​<h1>​Wait a minute...​</h1>​</body>​ 

现在我不知道为什么结果发生了这样的。
使用setTimeout()时,浏览器会忽略延迟并执行定时器功能,但不更新视觉事物的代码除外。这样对吗?

代码

<button onclick="func1()">Result</button> 
 
<script> 
 
\t function func1() { 
 
\t \t var newWindow = window.open('about:Blank', 'newWindow', 
 
\t \t \t 'width=480, height=272, resizable=1', true); 
 
\t \t if (newWindow) { 
 
\t \t \t var i = 3; 
 
\t \t \t var func = function() { 
 
\t \t \t \t var node = document.createElement('h1'); 
 
\t \t \t \t node.appendChild(document.createTextNode("Wait a minute...")); 
 
\t \t \t \t console.log(newWindow.document.getElementsByTagName('body')[0]); 
 
\t \t \t \t newWindow.document.getElementsByTagName('body')[0].appendChild(node); 
 
\t \t \t \t if (--i > 0) { 
 
\t \t \t \t \t setTimeout(func, 1000); 
 
\t \t \t \t } 
 
\t \t \t }; 
 
\t \t \t setTimeout(func, 1000); 
 
\t \t } else { 
 
\t \t \t window.alert('Popup Blocked'); 
 
\t \t } 
 
\t } 
 
</script>

回答

1

修改的setTimeout等待5秒。

setTimeout(func, 5000); 

只要您获得了cosole的日志,就展开它。你会发现它符合你的期望。即 - 第一次迭代为1,第二次为2,第三次为3。

现在就来看你所看到的行为。这是因为在完成所有操作之前,您不会在控制台中展开(没有时间展开)<body>...</body>。浏览器执行一些延迟加载来进行优化。因此,它不会加载完整的主体,除非通过点击enter image description here来扩展它。如果您在所有超时完成后单击它,它将加载它此刻找到的正文的内容。

希望这可以解释你的行为。

相关问题