javascript检查执行时间

时间:2013-08-06 14:06:29

标签: 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) + 
"&ccPh=" + encodeURIComponent(ccPh) + 
"&ccPp=" + encodeURIComponent(ccPp) + 
"&ccU=" + encodeURIComponent(ccU);

现在我需要编写try / catch代码。 Catch部分应该在没有响应超过2秒的情况下中断执行此javascript。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果你想在javascript中执行一个长时间运行的操作,而你正在接近某些浏览器强制执行的脚本执行时间限制,那么你将不得不将你的功能分成多个部分,运行一个部分,一个非常short 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();