Suppose we want to generate 10 million random numbers. The general practice is as follows:
Copy codeThe Code is as follows:
Var numbers = [];
For (var I = 0; I <10000000; I ++ ){
Numbers. push (Math. random ());
}
However, when executing this code in IE, a window is displayed prompting you whether to stop the script. In this case, we first think of optimizing the loop body. But obviously, the loop body is very simple and there is no room for optimization. Even if you clear the loop body, the prompt still exists. Therefore, I came to the conclusion that in IE, once the number of loops exceeds a specific value, a prompt is displayed to stop the script.
The reason is found. How can this problem be solved? The first thing I think of is to divide 10 million cycles into several cycles with fewer times. For example, divide it into one hundred times and execute 100,000 cycles each time:
Copy 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 think. It knows that the total number of cycles is still 10 million. Therefore, we need to separate these one hundred cycles. Although Javascript is single-threaded, you can use setTimeout or setInterval to simulate multithreading. The entire code segment is optimized as follows:
Copy codeThe Code is 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 ();