function getTime() {
const d = new Date();
const secs = d.getSeconds();
const mins = d.getMinutes();
const hours = d.getHours();
return {
'hours': hours,
'mins': mins,
'secs': secs
}
}
let time = getTime();
setInterval(getTime, 1000);
setInterval(() => {
console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);
The time displayed doesn't change. It just continually runs, outputting the same time instead of showing a change each second...
time variable is declared only once, when script loads and stays in that state. Move it inside the interval to keep it updated.
function getTime() {
const d = new Date();
const secs = d.getSeconds();
const mins = d.getMinutes();
const hours = d.getHours();
return {
'hours': hours,
'mins': mins,
'secs': secs
}
}
setInterval(() => {
const time = getTime();
console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);
You are only setting the value of time once, to the value of getTime() at that moment.
If you want the value to change, you have to set the value again every iteration.
setInterval(() => {
var time = getTime();
console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With