I am having a hard time understanding why the browser does and does not freeze with awaiting the promises specified in the below HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Promise Test</title>
<style>
#myBlock{
height: 400px;
width: 400px;
background-color: black;
}
#myBlock:hover{
background-color: red;
}
</style>
</head>
<body>
<div id="myBlock"></div>
<br>
<button onclick="awaitPromise()">Await a promise</button>
<br>
<h3 id="status">Promise Status:</h3>
<script>
async function awaitPromise(){
document.getElementById("status").innerHTML = "Promise Status: Awaiting Promise";
await new Promise(resolve => setTimeout(resolve, 5000));
/*
await new Promise(()=>{
});
await new Promise(()=>{
while(true){
}
});
*/
document.getElementById("status").innerHTML = "Promise Status: Finished";
}
</script>
</body>
</html>
For the 1st promise:
I expected the browser to be frozen for 5 seconds since the promise would not be resolved for 5 seconds, but the browser never freezes.
For the 2nd and 3rd Promise:
I expected the browser to freeze since the function would be halted permanently. However, only the 3rd promise freezes the browser.
It appears to me that as long as the function given to the promise finishes, the gui will not freeze regardless of whether or not the promise is resolved.
Can someone explain to me why the browser does not freeze even when the awaitPromise function is not finished running? And also why does the browser freeze only when awaiting the 3rd promise? Thanks.