Consider this JavaScript Code:
<script type="text/javascript">
function loop(Message){
document.getElementById('output').innerHTML =
document.getElementById('output').innerHTML + Message + '</br>';
}
window.setInterval("loop('Message1')", 1000); //Prints "Message1" every 1 Seconds
window.setInterval("loop('Message2')", 3000); //Prints "Message2" every 3 Seconds
</script>
<body>
<div id="output"></div>
</body>
Output:
Message1
Message1
Message2
Message1
Message1
Message1
Message2
...
And now Consider this PHP-Code:
<?php
while(true){ // Print "Message1" every 1 Second
echo 'Message 1 </br>';
sleep(1);
}
while(true){ //This Code will never be executed,
echo 'Message 2 </br>'; //because the First Loop Blocks the Process!!!!!
sleep(3);
}
?>
Output:
Message1
Message1
Message1
Message1
Message1
Message1
...
Why doesn't the first JavaScript-Loop stop the whole Process like the first while-Loop in PHP?
I know that Javascript is SingleThreaded, so I suppose, that JavaScript can't just start a new Thread to process the Second Loop. So I am woundering how JavaScript doesn't block here?
Could someone explain it to me?