Andreas
Andreas

Reputation: 39

SetInterval() within setInterval() at different times

I would like to ask how is it possible to run a function every 60 seconds which has another timer inside it that only runs every 5 minutes

function systemTime() {
  let currentTime = new Date();
  let diem = "AM";
  let h = currentTime.getHours();
  let m = currentTime.getMinutes();
  let s = currentTime.getSeconds();

  if (h == 0) h = 12;
  if (h > 12) diem = "PM";
  if (h < 10) h = "0" + h;
  if (m < 10) m = "0" + m;
  if (s < 10) s = "0" + s;

  return {
     h: h.toString(),
     m: m.toString(),
     diem: diem
  }
}


async function serverTime() {
  let timeUrl = 'https://worldtimeapi.org/api/timezone/Europe';
  let response = await fetch(timeUrl);
  let data = await response.json();

  let timestamp = data.datetime;
  let time = timestamp.split('T')[1].split('.')[0];
  let timeArray = time.split(':');
  if(parseInt(timeArray[0]) > 12) timeArray[2] = 'PM'
  else timeArray[2]  = 'AM';

  return {
    h: timeArray[0],
    m: timeArray[1],
    diem: timeArray[2]
  }
}

async function clock() {
  let h, m, diem;
  let container = document.querySelector('#displayClock');
  container.innerHTML = `${h} : ${m}`;
  setInterval(() => clock(), 60000);
  // I would like to grab the server time every 5 min for comparison
  setInterval(() => {}, 60000*5) // set minutes and hours to the server time 

}

I would like to call the clock() function every 60s to display the time on a page but at the same time I would like to call the serverTime() function every 5 minutes to compare the values and take the serverTime if they are not the same.

Calling clock() every 60s isn't the problem. setInterval will solve this but if within it I set an Interval of 5 min then every 10 seconds there will be a new 5 min interval set?

Thankyou very much for your help.

Upvotes: 1

Views: 83

Answers (2)

Andreas
Andreas

Reputation: 39

I have used this to solve the issue and obtain what i wanted

/** * Display a digital clock * * @param {string} container - placement of the clock on the page */

function systemTime() {
    let currentTime = new Date();
    let diem = "AM";
    let h = currentTime.getHours();
    let m = currentTime.getMinutes();
    let s = currentTime.getSeconds();

    if (h == 0) h = 12;
    if (h > 12) diem = "PM";
    if (h < 10) h = "0" + h;
    if (m < 10) m = "0" + m;
    if (s < 10) s = "0" + s;

    return {
        h: h.toString(),
        m: m.toString(),
        diem: diem
    }
}

/**
 * Returns an object containing hours and minutes from the worldTimeAPI
 */
async function serverTime() {
    let timeUrl = 'https://worldtimeapi.org/api/timezone/Europe/Berlin';
    let response = await fetch(timeUrl);
    let data = await response.json();

    let timestamp = data.datetime;
    let time = timestamp.split('T')[1].split('.')[0];
    let timeArray = time.split(':');
    if(parseInt(timeArray[0]) > 12) timeArray[2] = 'PM'
    else timeArray[2]  = 'AM';

    console.log('Time fetched from world API');

    return {
        h: timeArray[0],
        m: timeArray[1],
        diem: timeArray[2]
    }
}

/**
 * Fires every 5 min and compares server and system times
 */
async function compareTime() {
    let server = await serverTime();
    let system = systemTime();
    let container = document.querySelector('#displayClock');
    if(system.h != server.h || system.m != server.m) container.innerHTML = `${server.h} : ${server.m} ${server.diem}`;
    else container.innerHTML = `${system.h} : ${system.m} ${system.diem}`;
    setInterval(() => compareTime(), 60000);
}

/**
 * Fires every 1 min and displays system time
 */
function displayTime() {
    let system = systemTime();
    let h = system.h;
    let m = system.m;
    let diem = system.diem;
    let container = document.querySelector('#displayClock');
    container.innerHTML = `${h} : ${m} ${diem}`;
    setInterval(() => displayTime(), 60000);
}

Upvotes: 0

David
David

Reputation: 218818

You are recursively setting intervals:

async function clock() {
  //...
  setInterval(() => clock(), 60000);
  setInterval(() => {}, 60000*5);
}

So every time you call clock (every minute), you are setting more and more intervals for both clock and, well, an empty function. (It looks like you forgot to try to call serverTime?)

If you want to call clock every 60 seconds, then just set an interval to call it every 60 seconds:

async function clock() {
  //...
}

setInterval(clock, 60000);

If you want to call serverTime every 5 minutes, then just set an interval to call it every 5 minutes:

async function serverTime() {
  //...
}

setInterval(serverTime, 300000);

There's no need to do this recursively. Doing so means that setting an interval is part of the operation being repeated, which isn't what you want.

Edit: To demonstrate the problem, watch your browser console on this link: https://jsfiddle.net/Laqt4oe5 How many times do you expect the number to increase every 3 seconds? How many times is it actually increasing?

Upvotes: 2

Related Questions