Javascript 引擎的單線程特性使得在處理一個較大的循環遍歷時會長時間獨佔線程,導致其它事件(例如用戶操作)無法及時響應,嚴重時造成卡頓甚至是假死現象。為解決上述問題,一種可行機制是將大的循環拆分成若干小的循環片段分片執行,使得Javascript 引擎有時機在各段之間插入執行其它事情,從而有效改善性能體驗
Ansync.js
函數 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 開始,結束;
this.process = function(範圍, 逾時)
{
if(範圍!=未定義)
{
workCallback = workCallback.bind(scope);
返回回呼 = 返回回呼 ? returnCallback.bind(scope) : 未定義;
}
if (count_of_segment == num_of_segment)
{
清除逾時(計時器);
if (returnCallback != undefined)
returnCallback();
}
其他
{
開始 = 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(開始、結束);
段數 = 1;
this.process();
}
其他
{
計時器 = setTimeout(function ansyncTimeout(){
if (workCallback(start, end)) //若函數傳回true則結束流程
{
count_of_segment = num_of_segment;
}
其他
{
段數;
}
this.scope.process();
}.bind({scope: this}),逾時==未定義? Ansync.TimeOut : 超時);
}
}
}
}
Ansync.TimeOut = 5;
方法很簡單,但是很實用,有項目相同需求的小夥伴參考下吧