40749

How to output to console in real time in Javascript?

Question:

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.

<pre class="snippet-code-js lang-js prettyprint-override">for (var i = 1; i <= 100000; i++) { console.log(i); }

Answer1:

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!

<pre class="snippet-code-js lang-js prettyprint-override">function doHeavyTask(params) { var totalMillisAllotted = params.totalMillisAllotted; var totalTasks = params.totalTasks; var tasksPerTick = params.tasksPerTick; var tasksCompleted = 0; var totalTicks = Math.ceil(totalTasks / tasksPerTick); var interval = null; if (totalTicks === 0) return; var doTick = function() { var totalByEndOfTick = Math.min(tasksCompleted + tasksPerTick, totalTasks); do { params.task(tasksCompleted++); } while(tasksCompleted < totalByEndOfTick); if (tasksCompleted >= totalTasks) clearInterval(interval); }; // Tick once immediately, and then as many times as needed using setInterval doTick(); if (totalTicks > 1) interval = setInterval(doTick, totalMillisAllotted / totalTicks); } // Do 10,000 console.logs, in chunks of 100, within 5 seconds doHeavyTask({ totalMillisAllotted: 5 * 1000, totalTasks: 10000, tasksPerTick: 100, task: function(n) { console.log(n + 1); } });

Answer2:

If you want a smoother output, I would suggest avoiding the for loop, and instead use requestAnimationFrame which will manage when to print out the results.

var counter = 0; var max = 100000; function myPrint(){ if(counter < max){ console.log(counter++); requestAnimationFrame(myPrint); } } myPrint();

Answer3:

<pre class="snippet-code-js lang-js prettyprint-override">for (let i = 1; i <= 10; i++) { //console.log(i); setTimeout(function(){console.log(i)},i*1000); }

here is how you can delay your console. use setTimeout to check the value of console.log value after 1sec(1000ms).

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Answer4:

One could feed an array of Promises to an Observable in order to achieve the desired outcome. Promises are now native to JavaScript and you can get the Observable from the <a href="http://reactivex.io/rxjs/" rel="nofollow">RxJS</a> library.

Here is an example:

<pre class="snippet-code-js lang-js prettyprint-override">const array = []; // This could also be a for of loop or a .map() function for (let i = 0; i <= 25; i++) { const promise = new Promise((resolve) => { // This could be any synchronous or asynchronous code setTimeout(() => { resolve(i); }, 1000 * i); }); array.push(promise); } var observable = Rx.Observable.from(array); observable.subscribe((promise) => { promise.then(result => console.log(result)); }); <pre class="snippet-code-html lang-html prettyprint-override"><script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>

Answer5:

Your statement is not valid. JavaScript handles the for loop synchronously.

Please check the following question: <a href="https://stackoverflow.com/questions/5050265/javascript-node-js-is-array-foreach-asynchronous" rel="nofollow">JavaScript, Node.js: is Array.forEach asynchronous?</a>

Recommend

  • Three.js Orbit Controls with Two (Toggled) Cameras
  • how to add two matrices with production rules
  • How to find out why Javascript is downloading so slowly?
  • Base Internationalization and “Could not find a storyboard named […]”
  • UITableView takes much longer to load when numberOfRows returns a large number
  • How to Divide an array on c#?
  • Making Cross Site Asynchronous HTTP Post from GWT Client
  • Connect Node.js with Oracle on Windows platform
  • Mongodb update() vs. findAndModify() performace
  • Is there any way of quickening monkeyrunner script execution?
  • It is possible use the same sql azure instance from two different cloud service of two different sub
  • Many to Many in Linq using Dapper
  • How can I prevent the need to copy strings passed to a avr-gcc C++ constructor?
  • SQL - Select lowest values with group by and order by?
  • Cypher - matching two different possible paths and return both
  • C# - Most efficient way to iterate through multiple arrays/list
  • Consuming a WCF service in a Java Client using wsHttpBinding
  • Combining two different ActiveRecord collections into one
  • Parse a date string in a specific locale (not timezone!)
  • Row Count Is Returning the incorrect number using RaptureXML
  • formatting the colorbar ticklabels with SymLogNorm normalization in matplotlib
  • How to get address from latitude and longitude android google map v2 [duplicate]
  • Is my CUDA kernel really runs on device or is being mistekenly executed by host in emulation?
  • Incrementing object id automatically JS constructor (static method and variable)
  • Trying to switch camera back to front but getting exception
  • Arrow is showed instead of the material design version hamburger icon. Why doesn't syncState in
  • Javascript + PHP Encryption with pidCrypt
  • Google cloud sdk not working when python points python3
  • Apache 2.4 - remove | delete | uninstall
  • Compare two NSDates in iPhone
  • SetUp method failed while running tests from teamcity
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • What are the advantages and disadvantages of reading an entire file into a single String as opposed
  • Django query for large number of relationships
  • Programmatically clearing map cache
  • reshape alternating columns in less time and using less memory
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?