简体   繁体   English

使用“ setTimeout()”时执行的顺序是什么?

[英]What is the sequence of execution when using “setTimeout()”?

I made a blank window using window.open(). 我使用window.open()创建了一个空白窗口。
And I added a string "Wait a minute..." 3 times with 1 second of delay. 然后我添加了一个字符串“ Wait a minutes ...” 3次,延迟时间为1秒。
Just before adding the string, I logged the window's body. 在添加字符串之前,我记录了窗口的主体。

The window showed strings as I expected, but console log was not. 窗口显示的字符串符合我的预期,但控制台日志却没有。

log 日志

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>​

Now I wonder why the result occurred like this. 现在我想知道为什么会这样发生。
When using setTimeout(), a browser ignore delay and execute timer function except codes which updates visual things. 使用setTimeout()时,浏览器将忽略延迟并执行计时器功能,但更新可视内容的代码除外。 Is it right? 这样对吗?

code

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

Modify the setTimeout to wait for 5 seconds. 修改setTimeout以等待5秒。

setTimeout(func, 5000);

As soon as you get the log in cosole, expand it. 一旦获得登录日志,请展开它。 You will find it to be consistent with your exppectation. 您会发现它与您的期望相符。 ie - 1 for the 1st iteration, 2 for the 2nd and 3 for the 3rd. 即-1代表第一次迭代,2代表第二迭代,3代表第三迭代。

Now coming to the behaviour you are seeing. 现在来看您所看到的行为。 This is because you do not expand(do not get time to expand) the <body>...</body> in the console before all of them are done. 这是因为在完成所有操作之前,您不会在控制台中展开(没有时间展开) <body>...</body> The browser does some lazy loading to have optimizations. 浏览器会进行一些延迟加载以进行优化。 So, it never loads the complete body unless on goes to expand it by clicking on 因此,除非通过单击展开它,否则它永远不会加载整个主体 在此处输入图片说明 . If you click on it later once all the timeouts are done, it loads the contents of the body that it finds at that moment. 如果您在所有超时完成后稍后单击它,它将加载当时找到的正文内容。

Hope this explains your behaviour. 希望这可以解释您的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM