JavaScriptエンジンのシングルレディング機能により、大きなループトラバーサルを処理する際に長い間排他的なスレッドが可能になり、他のイベント(ユーザー操作など)が時間内に応答できなくなり、重度の場合には遅れや偽の死を引き起こす可能性があります。上記の問題を解決するために、実行可能なメカニズムは、大きなループをいくつかの小さなループフラグメントに分割してフラグメントを実行することです。これにより、JavaScriptエンジンはセグメント間で他のものを挿入および実行する機会があり、それによりパフォーマンスエクスペリエンスを効果的に改善します。
ansync.js
コードコピーは次のとおりです。
function ansync(totalcount、segmentcount、workcallback、returncallback)
{
var num_of_item_for_each_segment = segmentcount;
var num_of_segment = math.ceil(totalcount / num_of_item_for_each_segment);
var count_of_segment = 0;
varタイマー;
var Start、end;
this.process = function(scope、timeout)
{
if(scope!=未定義)
{
workcallback = workcallback.bind(scope);
returnCallback = returnCallback? returnCallback.bind(scope):未定義;
}
if(count_of_segment == num_of_segment)
{
ClearTimeout(タイマー);
if(returncallback!=未定義)
returncallback();
}
それ以外
{
start = count_of_segment * num_of_item_for_each_segment;
end = math.min(totalcount、(count_of_segment + 1) * num_of_item_for_each_segment);
if(num_of_segment == 1)//タイマーを作成する必要はありません
{
workcallback(start、end);
count_of_segment = 1;
this.process();
}
それ以外
{
Timer = setimeout(function ansynctimeout(){
if(workcallback(start、end))// function関数がtrueを返す場合
{
count_of_segment = num_of_segment;
}
それ以外
{
count_of_segment ++;
}
this.scope.process();
} .bind({scope:this})、timeout == undefined? ansync.timeout:タイムアウト);
}
}
}
}
ansync.timeout = 5;
この方法は非常に単純ですが、非常に実用的です。同じプロジェクト要件がある場合は、参照してください。