SoFunction
Updated on 2025-03-01

js loop with too many optimizations, considering performance issues

Assuming that you want to generate 10 million random numbers, the general approach is as follows:
Copy the codeThe code is as follows:

var numbers = [];
for (var i = 0; i < 10000000; i++) {
(());
}

However, when executing this code under IE, a window pops up to prompt the user whether to stop the script. When this happens, the first thing that comes to mind is to optimize the loop body. But obviously, the circulation body is 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: in 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? The first thing I thought of was to divide 10 million cycles into several cycles with fewer cycles. For example, it is divided into 100 times, and each time it is performed a hundred thousand cycles:
Copy the codeThe code is as follows:

for (var i = 0, j; i < 100; i++) {
for (j = 0; j < 100000; j++) {
......
}
}

IE is not as stupid as we imagined, it knows that the total number of cycles is still 10 million. Therefore, these one hundred thousand cycles must be executed separately. Although Javascript is single threaded, it is also possible to simulate multithreading through setTimeout or setInterval. The whole code is optimized as follows:
Copy the codeThe code is as follows:

var numbers = [];
function begin() {
for (var i = 0; i < 100000; i++) {
(());
}
if ( < 10000000) { // Is it completed
setTimeout(begin, 0);
} else {
alert("complete");
}
}
begin();