In Javascript, when you write a piece of code like the one below, it seems like the computer will first complete the entire loop 100 000 times (which can take a second or two) and THEN dump all 100 000 lines in the console in one shot. How can I make it so that the computer will update the console one line at a time, with each pass thru the loop?
To clarify, I would like to, in effect, be able to see what the computer is doing AS it is doing it, and not once it has finished doing it.
for (var i = 1; i <= 100000; i++) {
console.log(i);
}
Browsers run script synchronously. If you want the page to update as a long task is running, you need to break your long-running synchronous code up into pieces, and relinquish control to the browser between the processing of these pieces. This means that you need to deal with breaking a series of tasks into chunks, and controlling the delays which return control to the browser.
Here's a snippet which provides a method that allows you to do exactly this! You'll notice the performance is still not great, but I'm quite sure this is due to the slowness of stackoverflow's embedded script runner's implementation of
console.log
. Try using this code in the browser's actual console - the performance is great!