I'm attempting to get time to update with JavaScript in a Node.js console, in my function indexActiveTime I gather the hours, minutes, and seconds, and input them to a console.log that is suppose to output them as the current system time in a formatted 00:00:00; I call the function at the end and run the node.js program and for some reason I only get the following output.
undefined:undefined:undefined
undefined:undefined:undefined
undefined:undefined:undefined
I've attempted to throw it into certain variables, different concat methods, and the only results I've received are it outputting as the variable, like so.
${callActiveHours}:${callActiveMinutes}:${callActiveSeconds}
or
function getHours() { [native code] }:function getMinutes() { [native code] }:function getSeconds() { [native code] }
function addZero(i) { if (i < 10) { i = "0" + 1; return i; } } function indexActiveTime() { var getIndexTime = new Date(); var callActiveHours = addZero(getIndexTime.getHours); var callActiveMinutes = addZero(getIndexTime.getMinutes); var callActiveSeconds = addZero(getIndexTime.getSeconds); console.log(callActiveHours + ":" + callActiveMinutes + ":" + callActiveSeconds); var activeTimeOut = setTimeout(indexActiveTime, 500); } indexActiveTime();
As the comments suggest:
i < 10
is falsei = '0' + 1
should be i = '0' + i
function addZero(i) { if (i < 10) { // Fix assignment i = "0" + i; return i; // Return i if condition is false } else { return i; } } function indexActiveTime() { var getIndexTime = new Date(); // Call methods, not just reference them var callActiveHours = addZero(getIndexTime.getHours()); var callActiveMinutes = addZero(getIndexTime.getMinutes()); var callActiveSeconds = addZero(getIndexTime.getSeconds()); console.log(callActiveHours + ":" + callActiveMinutes + ":" + callActiveSeconds); var activeTimeOut = setTimeout(indexActiveTime, 500); } indexActiveTime();
For how to create a timer that reasonably reliably runs at the required interval, see this answer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.