This article mainly introduces the solution that causes choppy by exclusive threads of the javascript engine for a long time, you can refer to the single-thread feature of the Javascript engine to prevent other events (such as user operations) from responding in a timely manner by taking a long time to exclusively process a large loop, in severe cases, choppy or even fake death occurs. To solve the above problem, a feasible mechanism is to split a large loop into several small loop fragments for multipart execution, so that the Javascript engine has the opportunity to insert and execute other tasks between each segment, this effectively improves the performance experience
Ansync. js
The Code is as follows:
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;
The method is very simple, but it is very practical. For more information, see