2017-07-16 88 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來擴展它。如果您在所有超時完成後單擊它,它將加載它此刻找到的正文的內容。

希望這可以解釋你的行爲。

相關問題