【发布时间】:2012-08-07 04:03:43
【问题描述】:
今天在 Firefox 中调试一些客户端 javascript 时,我遇到了一些我觉得很奇怪且有点令人不安的事情。此外,在使用 IE / VS2010 调试同一脚本时,我无法复制此行为。
我创建了一个简单的示例 html 文档来说明我看到的异常情况。
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js" type="text/javascript" ></script>
</head>
<body id="main_body">
<script type="text/javascript">
$(function () {
$(".test-trigger").on("click", function () {
loadStuff();
console && console.log && console.log("this will probably happen first.");
});
});
function loadStuff() {
$.get("http://google.com/")
.fail(function () {
console && console.log && console.log("this will probably happen second.");
});
}
</script>
<button class="test-trigger">test</button>
</body>
</html>
如果您将此文档加载到 Firefox(我在 Windows 7 上使用版本 13.0 和 Firebug 版本 1.10.1),单击测试,然后在 Firebug 中查看控制台选项卡,您应该注意到获取请求失败(跨域违规与我在这里要说明的观点无关),然后您很可能会看到:
this will probably happen first.
this will probably happen second.
现在,在第 13 行和第 20 行放置断点:
13: console && console.log && console.log("this will probably happen first.");
20: console && console.log && console.log("this will probably happen second.");
如果您再次单击测试,您将按预期中断第 13 行。现在,继续执行。如果您的经验和我一样,您不会在第 20 行中断。此外,如果您切换到控制台选项卡,您将看到以下日志输出序列:
this will probably happen second.
this will probably happen first.
对我来说,这表明 ajax 请求的失败处理程序正在一个线程中执行,而不是在其中执行单击处理程序的线程中。我一直被引导相信单个页面的所有 javascript 将由任何浏览器中的单个线程执行。我在这里错过了一些非常明显的东西吗?感谢您对此观察的任何见解。
哦,如果我使用 Visual Studio 调试在 IE 中运行的同一个页面,两个断点都会按预期命中。
【问题讨论】:
-
$.get 函数正在执行异步 ajax 查询。调用失败回调的速度取决于浏览器从 google.com 听到的速度。如果它足够快,它会在调用 console.log 函数之前进入。不足以判断它是否是线程的。
-
如果您的预期行为出现在浏览器中,那么长的 ajax 查询会使网页无法使用。
-
我在这里真正要问的是为什么在 firebug 中调试时不会同时访问第 13 行和第 20 行设置的断点。我不关心行的执行顺序。
-
你可以在 Ajax 回调中设置一个无限循环,看看会发生什么......
标签: javascript multithreading firefox firebug