Suppose you want to generate 10 million random numbers, the general practice is as follows:
Copy Code code 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:
Copy Code code as follows:
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:
Copy Code code 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 ();