The single-threaded nature of the Javascript engine makes it an exclusive thread for a long time to process a larger loop traversal, causing other events (such as user actions) to not respond in a timely manner, causing cotton even to suspend animation in serious cases. To solve the above problem, a feasible mechanism is to split a large loop into several small pieces of circular fragment execution, so that the JavaScript engine has the opportunity to insert between the segments to perform other things, thus effectively improve the performance experience
Ansync.js
Copy Code code 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 very practical, with the same project needs of the small partner reference