JavaScript 引擎是單線程的。當程式進入一個龐大的迴圈時,引擎會被長期佔用,其間使用者的點擊、輸入等操作都無法得到回應,嚴重的時候畫面甚至會呈現假死。要緩解這個問題,一種可行的機制是「分片」:把大迴圈切成若干小段,讓引擎在段與段之間有機會插入處理其他工作,回饋到使用者身上就是明顯順滑的體驗。
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 timer;
var start, end;
this.process = function(scope, timeout)
{
if (scope != undefined)
{
workCallback = workCallback.bind(scope);
returnCallback = returnCallback ? returnCallback.bind(scope) : undefined;
}
if (count_of_segment == num_of_segment)
{
clearTimeout(timer);
if (returnCallback != undefined)
returnCallback();
}
else
{
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)//needn't create timer
{
workCallback(start, end);
count_of_segment = 1;
this.process();
}
else
{
timer = setTimeout(function ansyncTimeout(){
if (workCallback(start, end)) //finish process if function returns true
{
count_of_segment = num_of_segment;
}
else
{
count_of_segment++;
}
this.scope.process();
}.bind({scope: this}),timeout == undefined ? Ansync.TimeOut : timeout);
}
}
}
}
Ansync.TimeOut = 5;
設計上值得注意的幾個細節:
· 分段計算:以 Math.ceil(totalCount / segmentCount) 算出總段數,每次 process 只處理 [start, end) 這一段。
· 讓出控制權:段與段之間用 setTimeout 打斷,預設間隔僅 5 毫秒,足以讓瀏覽器把事件佇列中的點擊、繪圖排進來。
· 提前終止:workCallback 回傳 true 時視為任務完成,直接把計數器推到末段,迴圈即刻收尾。
· 單段快速路徑:若只需一段(num_of_segment == 1),完全不建立定時器,避免不必要的延遲。
· scope 綁定:透過 bind 保留 this 指向,讓回呼能在正確的上下文中執行。
這裡有一個值得留意的細節:定時器回呼中呼叫的是 this.scope.process(),而 scope 是在 .bind({scope: this}) 時才掛上的,第一次呼叫 process 若未傳入 scope,這行會出錯。實務上可改為在建構時就保存 var self = this,回呼內直接呼叫 self.process(),會更穩妥。
最後補充一個現代對照:ES6 之後,requestAnimationFrame 適合處理需要畫面更新的分片任務,而 requestIdleCallback 則能在瀏覽器閒置時段見縫插針;若任務本身極重且不需要操作 DOM,直接丟進 Web Worker 才是根治之道——那樣完全不佔用主線程,也就不存在卡頓問題。
方法簡單但實用,有類似需求的讀者可以參考。