0

I'm trying to create a function that can return a value (the user's current time in seconds) to another variable that can be used elsewhere in my code. The function returns the correct value, but I can't figure out how to make it repeat using setInterval or setTimeout.

var currenttime = clock();

function clock() {
    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    var time = (hour * 3600) + (minute * 60) + second;
    return time;
}

console.log(currenttime)

I want the variable currenttime to be updated every second, but changing the line to
var currenttime = setInterval(clock, 1000);
returns an incorrect value. Alternatively I've also tried to make the clock function repeat,
but I'm not sure how to do this as I'm using a return statement so the function ends before it can be repeated.

Does anyone know what I'm doing wrong?

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
wrgt
  • 158
  • 10
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – SuperStormer Apr 05 '20 at 22:02

3 Answers3

0

Assign to currentTime every time clock runs, but don't return the time - since this'll be in an interval, the return value is ignored:

let currentTime;

function clock() {
    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    currentTime = (hour * 3600) + (minute * 60) + second;
}

setInterval(clock, 1000);

setTimeout(() => console.log(currentTime), 2000);
setTimeout(() => console.log(currentTime), 6000);

This is a bit weird, though - variable assignment alone doesn't have side effects (in almost all cases). It would make more sense for whatever uses the currentTime variable to call clock to get the current number of seconds, eg:

function clock() {
    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    return (hour * 3600) + (minute * 60) + second;
}

document.querySelector('button').addEventListener('click', () => {
  document.querySelector('div').textContent = clock();
});
<button>Get seconds</button>
<div id="time"></div>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

setInterval return only an ID value that can be used in clearInterval(ID) to stop setInterval loop.

So, you can do that:

function clock()
  {
  let [h,m,s] = (new Date().toTimeString()).match(/\d{2}/g)
  return (h*3600) + (m*60) + +s
  }

var currenttime = clock();
setInterval(() => { currenttime = clock() }, 1000);
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
0

The function called by setInterval should call clock and display the time.

setInterval(function(){ console.log(clock()); }, 1000);
QuentinUK
  • 2,997
  • 21
  • 20