I have an application that I have to push to the array with multi-valued values, so I check the runtime:
var st = new Date().getTime(); var a = []; for (var i = 0; i < 20971520; i++) { a.push(i); } var ed = new Date().getTime(); console.info((ed - st) / 1000); console.info(a.length);
I run the codes in the Firefox console and Chrome console, and it costs 37 seconds . And at runtime, even the mouse can be moved in Chrome, but there is no interactive effect.
Then I change the codes:
function push() { var st = new Date().getTime(); var a = []; for (var i = 0; i < 20971520; i++) { a.push(i); } var ed = new Date().getTime(); console.info((ed - st) / 1000); console.info(a.length); } var tr = setTimeout(push, 50);
Simplify put codes in a function and call it with setTimeout , it costs 0.844 second . And at runtime, I can work fine in Chrome.

What's going on here?
I know that setTimeout will put the control in the browser to do the user interface job, which will make the page susceptible. For example, when I do some calculations during the mousemove page, I would set the calculation to be delayed to prevent the user interface from blocking it.
But why does this reduce the overall execution time of the same codes?
source share