JavaScript engine long-time exclusive threading results in a cotton solution _javascript tips

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.