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?
Because
setIntervalis specifically notsleep.setIntervalis more like a scheduler. It marks a time at which something should be executed and lets the main thread forget about it completely until that time arrives.sleepon the other hand is basically a no-op loop, which lets nothing else execute while it’s looping.This is important, since the use cases for PHP and Javascript are entirely different. A PHP script has a start and an end and it executes in a linear fashion. Javascript is used for interactivity, which means it needs to respond to various things (mouse clicks, keyboard input, timers, AJAX callbacks) in a non-linear fashion as they happen. If the main thread was blocked waiting for a timer, nothing would happen and the interface would appear frozen.
Here’s a good article by jQuery’s John Resig about Javascript timers: http://ejohn.org/blog/how-javascript-timers-work/