0

I have code that fetches time differences in UTC, but it outputs straight to HTML. I want to store the results of the function to use later, such that in the example below, r1 and r2 stores the result of responseText based on the 'timezone' passed. How can I do this?

<!-- <input type="button" value="Get Current Time" onclick="getTime()"> -->
<p id="responseText"></p>
function getTime(timezone) {
  $.get("https://worldtimeapi.org/api/timezone/" + timezone, null, function(data) {
    $("#responseText").text(data.raw_offset)
  })
};

var r1 = getTime("Asia/Kolkata");
var r2 = getTime("Europe/Copenhagen");
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
John
  • 29
  • 3

2 Answers2

4

One way, is to use async/await and wait for the async $.get() method to return the result and then store the result in two variables. But, for that also, you'll need an async function.

async function getTime( timezone ){

  const data = await $.get( "https://worldtimeapi.org/api/timezone/" + timezone );
  return data.raw_offset;

}

// You need to place you main application code in an async function since you will be `awaiting` for the result of two other async functions:
async function init(){

  let r1 = await getTime("Asia/Kolkata");
  let r2 = await getTime("Europe/Copenhagen");
  console.log( r1, r2 );

}

init();

Codepen


Alternatives:

  • You can drop jQuery and use fetch() as Traveling Tech Guy proposes.
  • You can use Promises instead of async/await, but that will make the code a lot harder to read and write
Kostas Minaidis
  • 4,681
  • 3
  • 17
  • 25
0

You can use await, async and fetch to get what you need. This code works:

<html>
<script>
async function getTime(timezone = '') {
  try {
    let response = await fetch("https://worldtimeapi.org/api/timezone/" + timezone);
    let result = await response.json();
    // $("#responseText").text(result.raw_offset);
    return result.raw_offset;
  }
  catch(err) {
    console.error(err);
    return null;
  }
}

(async function() {
  let diff = await getTime('Asia/Kolkata');
  console.log(diff)
}());
</script>
</html>

Notice that if timezone is not passed to the function, we set it to an empty string, to avoid garbage (which you may get in your original implementation).

Traveling Tech Guy
  • 27,194
  • 23
  • 111
  • 159