How to Print a Variable Inside a for Loop to the Console in Real Time as the Loop Is Running

How to print a variable inside a for loop to the console in real time as the loop is running?

The last one does print in real time, try it like this:

for(i in 1:10){
Sys.sleep(0.1)
print(i)
}

This looks fine in Rstudio, but in classic Rgui you have to click the console in order to it to refresh (increasing the sleep for example by Sys.sleep(0.5) helps to see that). You can circumvent that by using flush.console which clears the buffer:

for(i in 1:10){
Sys.sleep(0.1)
print(i)
flush.console()
}

Or in Windows you can select Misc in the upper toolbar and uncheck the buffered output.


If your goal is to track the process of your loop, the above method feels bit akward (at least to my eyes) when you are running through large number of iterations. In that case it might be nicer to use progress bars:

n<- 1000
pb <- txtProgressBar(min = 0, max = n, style = 3) #text based bar
for(i in 1:n){
Sys.sleep(0.001)
setTxtProgressBar(pb, i)
}
close(pb)

Or something even nicer:

library(tcltk)
n<- 1000
pb <- tkProgressBar(title = "Doing something", min = 0, max = n, width = 200)
for(i in 1:n){
Sys.sleep(0.001)
setTkProgressBar(pb, i, label=paste(round(i/n*100,1),"% done"))
}
close(pb)

How to print a variable inside a for loop to the console in real time as the loop is running?

The last one does print in real time, try it like this:

for(i in 1:10){
Sys.sleep(0.1)
print(i)
}

This looks fine in Rstudio, but in classic Rgui you have to click the console in order to it to refresh (increasing the sleep for example by Sys.sleep(0.5) helps to see that). You can circumvent that by using flush.console which clears the buffer:

for(i in 1:10){
Sys.sleep(0.1)
print(i)
flush.console()
}

Or in Windows you can select Misc in the upper toolbar and uncheck the buffered output.


If your goal is to track the process of your loop, the above method feels bit akward (at least to my eyes) when you are running through large number of iterations. In that case it might be nicer to use progress bars:

n<- 1000
pb <- txtProgressBar(min = 0, max = n, style = 3) #text based bar
for(i in 1:n){
Sys.sleep(0.001)
setTxtProgressBar(pb, i)
}
close(pb)

Or something even nicer:

library(tcltk)
n<- 1000
pb <- tkProgressBar(title = "Doing something", min = 0, max = n, width = 200)
for(i in 1:n){
Sys.sleep(0.001)
setTkProgressBar(pb, i, label=paste(round(i/n*100,1),"% done"))
}
close(pb)

Is it possible to manually change/update a variable inside a loop while it is running in python

Since python is by default thread-locking, you cannot change the value of your variable without designing your code to do so. However, if you are using threads (see threading docs here), you can create two different threads which will run parallel, asynchrously. By accesssing the same variable (needs to be in same scope or global), you can change it while your loop is still running.

It is, however, not best practice to do so since most of the time you can't tell which operation will happen first due to how CPUs will process their work.

How to output to console in real time in Javascript?

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 secondsdoHeavyTask({ totalMillisAllotted: 5 * 1000, totalTasks: 10000, tasksPerTick: 100, task: function(n) { console.log(n + 1); }});

JavaScript closure inside loops – simple practical example

Well, the problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function.

ES6 solution: let

ECMAScript 6 (ES6) introduces new let and const keywords that are scoped differently than var-based variables. For example, in a loop with a let-based index, each iteration through the loop will have a new variable i with loop scope, so your code would work as you expect. There are many resources, but I'd recommend 2ality's block-scoping post as a great source of information.

for (let i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("My value: " + i);
};
}

Beware, though, that IE9-IE11 and Edge prior to Edge 14 support let but get the above wrong (they don't create a new i each time, so all the functions above would log 3 like they would if we used var). Edge 14 finally gets it right.



ES5.1 solution: forEach

With the relatively widespread availability of the Array.prototype.forEach function (in 2015), it's worth noting that in those situations involving iteration primarily over an array of values, .forEach() provides a clean, natural way to get a distinct closure for every iteration. That is, assuming you've got some sort of array containing values (DOM references, objects, whatever), and the problem arises of setting up callbacks specific to each element, you can do this:

var someArray = [ /* whatever */ ];
// ...
someArray.forEach(function(arrayElement) {
// ... code code code for this one element
someAsynchronousFunction(arrayElement, function() {
arrayElement.doSomething();
});
});

The idea is that each invocation of the callback function used with the .forEach loop will be its own closure. The parameter passed in to that handler is the array element specific to that particular step of the iteration. If it's used in an asynchronous callback, it won't collide with any of the other callbacks established at other steps of the iteration.

If you happen to be working in jQuery, the $.each() function gives you a similar capability.



Classic solution: Closures

What you want to do is bind the variable within each function to a separate, unchanging value outside of the function:

var funcs = [];

function createfunc(i) {
return function() {
console.log("My value: " + i);
};
}

for (var i = 0; i < 3; i++) {
funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}


Related Topics



Leave a reply



Submit