Donggi Kim
Donggi Kim

Reputation: 402

What is the sequence of execution when using "setTimeout()"?

I made a blank window using window.open().
And I added a string "Wait a minute..." 3 times with 1 second of delay.
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. 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>

Upvotes: 0

Views: 52

Answers (1)

Rajeev Ranjan
Rajeev Ranjan

Reputation: 4076

Modify the setTimeout to wait for 5 seconds.

setTimeout(func, 5000);

As soon as you get the log in cosole, expand it. You will find it to be consistent with your exppectation. i.e - 1 for the 1st iteration, 2 for the 2nd and 3 for the 3rd.

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. 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 enter image description here . 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.

Upvotes: 1

Related Questions