有时我发现,JavaScript 有多个线程,这让我很恼火。我上网查了一下,发现总是有人说只有一个线程,但我遇到的不止一个。您可以将代码复制到 html 文件中,然后运行。你会明白我的意思。为什么 javascript 有多个带有警报、确认、提示的线程?谢谢阅读。
注意:要对其进行测试,您应该获取 jQuery 并替换它。
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.2.js"></script>
<script type="text/javascript">
function pauseWithAlert(){
fireAjax();
alert("pause at one thread, I guess before this OK is clicked, no javascript should be executed since single thread, and the runner is with this thread in this function fpause");
}
function pauseWithConfirm(){
fireAjax();
if(confirm("the message has been triggered, while the 1st thread is paused with this confirmation request, but the message from another thread has been presented to you")){
//something;
}
}
function pauseWithDeadLoop(){
alert("after you click OK, I will trigger the message, and then let the 1st thread get into dead loop, you will not be able to see the message");
fireAjax();
while(true);
}
function fireAjax(){
var location = document.location.toString();
$.ajax({type:'get',dataType:'html',url:location,success: ajaxSuccess, error: ajaxError});
}
var message = "have you clicked the OK in the 1st thread, this is a message from 2nd thread, isn't it?";
function ajaxSuccess(){
document.getElementById('ajaxmessage').textContent = message;
}
function ajaxError(){
document.getElementById('ajaxmessage').textContent = message;
}
function clearMessage(){
document.getElementById('ajaxmessage').textContent = "";
}
</script>
</head>
<body>
I know that it was said javascript is just one thread.
However, I found that sometimes, it is not just one thread.
<br/>Click <span onclick="pauseWithAlert();">here to pause with an alert</span> or
<span onclick="pauseWithConfirm();">here to pause with a confirm</span>,
and the runner stops there in the 1st thread, but you will see a message from
another thread below, so not single thread????? No!!!
<br/>Click <span onclick="pauseWithDeadLoop();">here</span> to stop the 1st thread
with a dead loop, you will not see a message from another thread below.
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<span id=ajaxmessage></span>
<br/>
<span onclick="clearMessage();">Clear the above message</span>
</body>
</html>