Suppose you want to generate 10 million random numbers. The general approach is as follows:
var numbers = [];
for (var i = 0; i < 10000000; i ) {
numbers.push(Math.random());
}
However, when executing this code under IE, a window pops up asking the user whether to stop this script. When this happens, the first thing that comes to mind is optimizing the loop body. But obviously, the loop body is very simple and there is no room for optimization. Even if the loop body is cleared, the prompt still exists. So, I came to a conclusion: Under IE, once the number of loops exceeds a certain value, a prompt to stop the script will pop up.
The cause has been found, how to solve it? My first thought was to divide the 10 million loops into several smaller loops. For example, divide it into one hundred times and execute the loop one hundred thousand times each time:
for (var i = 0, j; i < 100; i ) {
for (j = 0; j < 100000; j ) {
...
}
}
IE is not as stupid as we think. It knows that the total number of cycles is still 10 million. Therefore, these one hundred thousand cycles have to be executed separately. Although Javascript is single-threaded, it can also simulate multi-threading through setTimeout or setInterval. The entire code is optimized as follows:
var numbers = [];
function begin() {
for (var i = 0; i < 100000; i ) {
numbers.push(Math.random());
}
if (numbers .length < 10000000) { // Whether it has been completed
setTimeout(begin, 0);
} else {
alert("complete");
}
}
begin ();