Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
676 views
in Technique[技术] by (71.8m points)

loops - How to output to console in real time in Javascript?

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);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!

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); }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...