-2

In browser, we can making the live clock in single line display by using setInterval and replacing content inside HTML element like this:

var span = document.getElementById('span');

    function time() {
      var d = new Date();
      var s = d.getSeconds();
      var m = d.getMinutes();
      var h = d.getHours();
      span.textContent = 
        ("0" + h).substr(-2) + ":" + ("0" + m).substr(-2) + ":" + ("0" + s).substr(-2);
    }
setInterval(time, 1000);
<span id="span"></span>

But, how we can do it the same thing in terminal console with NodeJS? If we use console.log and setInterval it will create new line. Like this:

07:00:01
07:00:02
07:00:03
07:00:04

I just want to display console.log live clock in single line on terminal.

  • @jarmod No, still need example code to display live clock in single line console.log terminal .. Which is need forever loop implementation like setInterval – Adam Satria Gunadi Oct 22 '21 at 00:24

1 Answers1

2

You w ant to use \r to terminate the previous line with stdout.

    setInterval(() => process.stdout.write(`${new Date()}\r`), 1000);
Michael Mano
  • 3,339
  • 2
  • 14
  • 35