Update new Date every function call

Viewed 28

I have a function (called metro) that uses the current local time. I also have a setInterval() that calls this function every 30 seconds, but the setInterval() is returning always the same value, when my intention is that the time gets updated by the new Date()

let now = new Date()
let hourNow = now.getHours()
let minutesNow = now.getMinutes()
const interval = setInterval(metro, 30000, hourNow, minutesNow);
3 Answers

If you want the times to change you'll need to create your date and the other variables inside the interval function.

const interval = setInterval(() => {
  let now = new Date()
  let hourNow = now.getHours()
  let minutesNow = now.getMinutes()
  metro(hourNow, minutesNow);
}, 30000);

You can use this approach:

let now , hourNow , minutesNow;

function metro(){
now = new Date()
hourNow = now.getHours()
minutesNow = now.getMinutes()
}

setInterval(metro , 30000)

declearing the vairables in the global scope will allow them to be updated when the function is called and accessed outside the function too.

Key point

declearing the now = new Date() inside the metro function will give you the new time every time the function is called by the setInterval function.

thank you

The setInterval() function doesn't return the same return value from metro() function. It returns intervalID numeric value representing the interval created. You can check MDN for more details: https://developer.mozilla.org/en-US/docs/Web/API/setInterval#return_value

In order to update the date value each time setInterval() is triggered, you need to move the new Date() inside the setInterval() callback function:

const interval = setInterval(() => {
    const now = new Date();
    const hourNow = now.getHours();
    const minutesNow = now.getMinutes();

    metro(hourNow, minutesNow);
}, 30000);
Related