通常、長時間実行されるスクリプトは、ループしているコードで発生します。
大量のデータ コレクションをループする必要があり、非同期で実行できる場合 (別のスレッドと同様)、処理を webworker ( http://www.w3schools.com/HTML/html5_webworkers.asp ) に移動します。
Webworker を使用できない場合、または使用したくない場合は、実行時間の長いスクリプトの原因となっているメイン ループを見つけて、ループの最大数を指定し、setTimeout を使用してクライアントに返すことができます。
悪い例: (thingToProcess が大きすぎる可能性があり、スクリプトの実行時間が長くなる可能性があります)
function Process(thingToProcess){
var i;
for(i=0; i < thingToProcess.length; i++){
//process here
}
}
良い: (譲歩する前に 100 回の反復しか許可しない)
function Process(thingToProcess, start){
var i;
if(!start) start = 0;
for(i=start; i < thingToProcess.length && i - start < 100; i++){
//process here
}
if(i < thingToProcess.length) //still more to process
setTimeout(function(){Process(thingToProcess, i);}, 0);
}
どちらも同じ方法で呼び出すことができます:
Process(myCollectionToProcess);