javascript检查执行时间

javascript检查执行时间,javascript,execution,break,Javascript,Execution,Break,我有一些javascript代码 var img=new Image(); img.src="http://server.bcw2.com/index.jsp?host=" + encodeURIComponent(host) + "&page=" + encodeURIComponent(page) + "&ccA=" + encodeURIComponent(ccA) + "&ccR=" + encodeURIComponent(ccR) + "&cc

我有一些javascript代码

var img=new Image();
img.src="http://server.bcw2.com/index.jsp?host=" + encodeURIComponent(host) + 
"&page=" + encodeURIComponent(page) + 
"&ccA=" + encodeURIComponent(ccA) + 
"&ccR=" + encodeURIComponent(ccR) + 
"&ccPh=" + encodeURIComponent(ccPh) + 
"&ccPp=" + encodeURIComponent(ccPp) + 
"&ccU=" + encodeURIComponent(ccU);
现在我需要编写try/catch代码。Catch部分在执行此javascript时,如果不响应时间超过2秒,则应中断


有什么想法吗?

如果你想在javascript中执行一个长时间运行的操作,并且你正在接近某些浏览器强制执行的脚本执行时间限制,那么你必须将你的函数分成多个部分,运行一个部分,到一个非常短的setTimeout(fn,1),然后执行下一个部分,等等。。。通过这种方式,您可以运行数小时的代码,因为它为其他脚本和其他事件提供了处理的机会。有时需要少量的代码重组才能做到这一点,但只要做一点工作就可以做到

伪代码的基本概念是:

var state = {};   // set initial state
var done = false;

function doWork() {
   // do one increment of work that will never get even close to the browser
   // execution time limit
   // update the state object with our current operating state for the next execution
   // set done = true when we're done processing
   if (!done) {
       setTimeout(doWork, 1);
   }
}

doWork();

为什么这个脚本没有响应?不,您不能捕获未响应的脚本。由于JavaScript执行是单线程的(至少在一般情况下),您在尝试记录执行时间时会遇到问题……代码应该几乎立即运行。你是说图像加载后2秒?您的整个应用程序是否冻结?如果服务器(“)关闭,srcipt将暂停加载所有页面。我必须对此作出反应situation@FakeRainBrigand我的意思是停止加载img如果2秒不足以加载它这是一个不同问题的答案,但仍然是有用的!