Pavel
Pavel

Reputation: 35

How to add some literal in console with console.log (or another command) command in same line?

How to print some literal in console with console.log (or another command) command in same line?

For example:

print 1;
print 2;
print 3;

Console output: 123

Upvotes: 1

Views: 64

Answers (1)

Cerbrus
Cerbrus

Reputation: 72857

Assuming I understood you correctly, you want a JavaScript equivalent of C#'s Console.Write, that appends (a) character(s) to the last line.

That's not possible.

The moment something is logged to the console, you no longer have access to it. You can't "append" to a logged line, you can't change it.


That said, you could write a wrapper that sortof emulates this behavior:

let logTimeout;        // Keep track of the pending timeout
let logArguments = []; // Keep track of the passed loggable arguments


function log(...args) {
  if (logTimeout) {
    logTimeout = clearTimeout(logTimeout);  // Reset the timeout if it's pending.
  }

  logArguments = logArguments.concat(args); // Add the new arguments.
  
  logTimeout = setTimeout(() => {           // Log all arguments after a short delay.
    console.log(...logArguments);
    logArguments.length = 0;
  });
}

log(1);
log(2);
log(3);
log("foo");
log("bar");
log({crazy: "stuff"});

setTimeout(() => {
  log(4);
  log(5);
  log(6);
  log("baz");
  log("woo");
  log([{crazier: "stuff"}]);
}, 500);

Just note that this logger is asynchronous. This means your code that calls log will run to completion before something is actually logged.

Upvotes: 1

Related Questions