简体   繁体   English

javascript检查执行时间

[英]javascript check time of execution

I have some javascript code. 我有一些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);

Now i need write try/catch code. 现在我需要编写try / catch代码。 Catch section should break executing this javascript when it non responding longer than 2 seconds. 当Catch部分没有响应超过2秒时,应该会中断执行此JavaScript。

Any ideas? 有任何想法吗?

If you want to execute a long running operation in javascript and you are getting anywhere close to the script execution time limit enforced by some browsers, then you will have to break your function into multiple pieces, run one piece, to a very short setTimeout(fn, 1) and then execute the next piece, etc... Doing it this way, you can run code for hours because it gives other scripts and other events a chance to process. 如果要在JavaScript中执行长时间运行的操作,而您却接近某些浏览器所强制执行的脚本执行时间限制,则必须将函数分成多个部分,然后运行一次,直到很短的setTimeout( fn,1),然后执行下一部分,依此类推。这样做,您可以运行几个小时的代码,因为它为其他脚本和其他事件提供了处理的机会。 It sometimes requires a minor amount of code restructuring to be able to do this, but it's always possible with a little work. 有时需要进行少量的代码重组就可以做到这一点,但是只需做一些工作就可以实现。

The basic concept in pseudo-code would be this: 伪代码的基本概念是这样的:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM