The timer must be initialized and the seconds have to be incremented each second. Can someone help me? I am not sure what is going on.
function timer(){
let seconds = "00";
let minutes = "00";
let hours = "00";
let fulltime = `${hours}:${minutes}:${seconds}`;
const incrementSeconds = () => {
secondsAsNumber = parseInt(seconds) 1;
seconds = secondsAsNumber.toString();
}
const displayTime = () => {
console.log(fulltime);
}
setInterval(() => {
incrementSeconds();
displayTime();
}, 1000);
}
timer();
It logs:
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
00:00:00
CodePudding user response:
Here's What u need
function timer() {
let seconds = "0";
let minutes = "0";
let hours = "0";
let fulltime = `${hours}:${minutes}:${seconds}`;
const incrementSeconds = () => {
let secondsAsNumber = parseInt(seconds) 1;
seconds = secondsAsNumber.toString();
if (seconds > 59) {
minutes = parseInt(minutes) 1;
seconds = 0;
}
if (minutes > 59) {
hours = parseInt(hours) 1;
minutes = 0;
}
// Update fulltime variable
fulltime = `${hours < 10 ? "0" hours : hours}:${
minutes < 10 ? "0" minutes : minutes
}:${seconds < 10 ? "0" seconds : seconds}`;
};
const displayTime = () => {
console.log(fulltime);
};
setInterval(() => {
incrementSeconds();
displayTime();
}, 1000);
}
timer();
CodePudding user response:
Update your fulltime
variable after incrementing seconds:
function timer(){
let seconds = "00";
let minutes = "00";
let hours = "00";
let fulltime = `${hours}:${minutes}:${seconds}`;
const incrementSeconds = () => {
secondsAsNumber = parseInt(seconds) 1;
seconds = secondsAsNumber.toString();
// Update fulltime variable
fulltime = `${hours}:${minutes}:${seconds < 10 ? "0" seconds : seconds}`;
}
const displayTime = () => {
console.log(fulltime);
}
setInterval(() => {
incrementSeconds();
displayTime();
}, 1000);
}
timer();
Then it should output:
00:00:01
00:00:02
00:00:03
00:00:04
00:00:05
... and so on ...