考慮這段JavaScript代碼:爲什麼JavaScript阻止?
<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
...
現在考慮這個PHP-代碼:
<?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
...
爲什麼不第一JavaScript的循環停止,整個過程就像第while循環在PHP ?
我知道Javascript是SingleThreaded,所以我想,JavaScript不能只是開始一個新的Thread來處理Second Loop。所以我正在弄傷JavaScript如何不阻擋在這裏?
有人能解釋給我嗎?
JavaScript是否像「事件循環」一樣工作? –
不確定你是什麼意思的事件循環,但如果真的想了解發生了什麼事閱讀這篇博文:http://dmitrysoshnikov.com/ecmascript/chapter-1-execution-contexts/ –
是的,它的工作就像一個事件循環 –