I'm trying to get the time to display on the terminal, pretty simple. I want every console.log to be a different second. Instead of running an infinite while loop like a neanderthal, I wanted node js to wait a second before running the function. However, this doesn't seem to work as it keeps printing the same time over and over again for maybe a couple of seconds, and then I get a RangeError since I exceeded the call stack size (whatever that means). I copied this from working code in a JavaScript/HTML app I made, which works perfectly, but I'm assuming node doesn't like some of it. Ideas?
function addZeroes(num) {
if (num < 10) {
var new_num = "0" + num
} else {
var new_num = num
}
return new_num
}
function timeClock(){
var refresh=1000; // Refresh rate in milli seconds
mytime = setTimeout(timeDisplay() , {}, refresh)
}
function timeDisplay() {
//creating elements
rightNow = new Date();
minute = rightNow.getMinutes();
hour = rightNow.getHours();
seconds = rightNow.getSeconds();
theTime = ""
theTime += addZeroes(hour) + ":" + addZeroes(minute) + ":" + addZeroes(seconds);
//displaying elements
console.log(theTime)
timeClock()
}
timeDisplay()
I assume the first function is irrelevant to the problem, but I don't know at this point.
For this, you don't want to use setTimeout but rather setInterval.
Example code:
function addZeroes(num) {
let new_num;
if (num < 10) {
new_num = "0" + num
} else {
new_num = num
}
return new_num
}
function timeClock(){
const refresh=1000; // Refresh rate in milli seconds
let mytime = setInterval(timeDisplay, refresh)
}
function timeDisplay() {
//creating elements
let rightNow = new Date();
let minute = rightNow.getMinutes();
let hour = rightNow.getHours();
let seconds = rightNow.getSeconds();
let theTime = "";
theTime += addZeroes(hour) + ":" + addZeroes(minute) + ":" + addZeroes(seconds);
//displaying elements
console.log(theTime);
}
timeClock();
If your end goal is bigger than printing to terminal, I'd recommend working with libraries like dayjs or momentjs, that have numerous helper functions rather than adding zeroes.
EDIT: You also probably want to end the execution of this function programatically. For this matter, use clearInterval() with your variable myTime as a parameter.