I have an HTML code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>demo</title>
</head>
<body>
<script src="./script1.js"></script>
<script src="./script2.js"></script>
<script>
console.log('inline-111')
setTimeout(() => {
console.log('inline-setTimeout-111')
}, 0);
</script>
<script>
console.log('inline-222')
setTimeout(() => {
console.log('inline-setTimeout-222')
}, 0);
setTimeout(() => {
console.log('inline-setTimeout-333')
}, 0);
new Promise(resolve => {
console.log('inline-Promise1')
resolve()
})
.then(function () {
console.log('inline-promise2')
})
.then(function () {
console.log('inline-promise3')
})
</script>
</body>
</html>
The first script tag code.
console.log("external-111");
setTimeout(() => {
console.log("setTimeout-external-111");
}, 0);
The second script tag code.
console.log("external-222");
setTimeout(() => {
console.log("setTimeout-external-222");
}, 0);
setTimeout(() => {
console.log("setTimeout-external-333");
}, 0);
new Promise((resolve) => {
console.log("external-Promise1");
resolve();
})
.then(function () {
console.log("external-promise2");
})
.then(function () {
console.log("external-promise3");
});
When running in Google Chrome(Chrome119.0.6045.200), the result is
external-111
setTimeout-external-111
external-222
external-Promise1
external-promise2
external-promise3
inline-111
inline-222
inline-Promise1
inline-promise2
inline-promise3
setTimeout-external-222
setTimeout-external-333
inline-setTimeout-111
inline-setTimeout-222
inline-setTimeout-333
When running in Firefox(121.0.1), the result is
external-111
external-222
external-Promise1
external-promise2
external-promise3
inline-111
inline-222
inline-Promise1
inline-promise2
inline-promise3
setTimeout-external-111
setTimeout-external-222
setTimeout-external-333
inline-setTimeout-111
inline-setTimeout-222
inline-setTimeout-333
Why is the output on the second line inconsistent? Is there any kind-hearted friend who can try to explain?
At first, I wanted to understand how the event loop would run when multiple scripts were mixed in the browser. But the two running results caused confusion.
The simplest explanations is that the external scripts took a different amount of time to load. Notice this does not even depend on the browser, but will also differ between multiple loads of the page in the same browser.
If the second external script takes a longer time to load, the timeout scheduled in the first script may be run before the script executes. If it takes a shorter time to load, the timeout will run after the script executes (but still before the timeout - with the same millisecond value - scheduled by the second script).