JavaScript Tutorial: Tuning cycles with too many times

Source: Internet
Author: User

Suppose you want to generate 10 million random numbers, the general practice is as follows:
var numbers = [];
for (var i = 0; i < 10000000; i++) {
Numbers.push (Math.random ());
}

However, when the code was executed under IE, a window was popped to prompt the user whether to stop the script. In this case, the first thought is to optimize the circulation body. But obviously, the circulation body is very simple, there is no room for optimization. Even if the circulation body is emptied, the hint still exists. So, I have come to a conclusion: in IE, once the number of loops more than a certain value, will pop-up stop the script prompts.

The reason has found, how to solve it? The first thing I thought of was dividing the 10 million cycles into several less cycles. For example, divide into 100 times, perform 100,000 cycles at a time:
for (var i = 0, J; i < i++) {
for (j = 0; J < 100000; J + +) {
......
}
}

IE is not as stupid as we think, it knows the total number of cycles or 10 million times. Therefore, the 100 100,000 cycles have to be implemented separately. Although JavaScript is single-threaded, it can also simulate multithreading through settimeout or setinterval. The whole piece of code is optimized as follows:
var numbers = [];
Function begin () {
for (var i = 0; i < 100000; i++) {
Numbers.push (Math.random ());
}
if (Numbers.length < 10000000) {//is completed
settimeout (begin, 0);
} else {
Alert ("complete");
}
}
Begin ();

Author:heero



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.