Assuming that 10 million random numbers are to be generated, the conventional 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 prompting 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 reason 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 one hundred thousand loops 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 loops is still ten 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) { // 是否已完成 setTimeout(begin, 0); } else { alert("complete"); } } begin();
More js optimization loops with too many times. Considering performance issues, please pay attention to the PHP Chinese website for related articles!