Firstly, your code needs some cleanup:
- You are missing the ending
; (semi-colon)
in the following two lines:
var track = data["recenttracks"]["track"][0]["name"]
var artist = data["recenttracks"]["track"][0]["artist"]["#text"]
Your get_data_from_api
function doesn't need any arguments, as you already have api_url
constant declared for the link to fetch the data
You do not refer to the api_url
from anywhere inside the get_data_from_api
function.
The Timing Tutorial at W3Schools has a very simple demo and I combined your code with theirs to demonstrate how it worked for me (except I don't have any API for last.fm so my data didn't show up, but the code ran):
<!DOCTYPE html>
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo">Current Time</p>
<p id="demo2">Fetch Data</p>
<p id="last">Fetch Time</p>
<script>
const api_url = "https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=flarely&api_key=key_here&format=json&limit=1";
var myVar = setInterval(myTimer, 1000);
var myVar2 = setInterval(get_data_from_api, 10000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = "Current Time: " + d.toLocaleTimeString();
}
// making an async function (non-async function won't work -_-)
async function get_data_from_api() {
// data
var d2 = new Date();
document.getElementById("last").innerHTML = "Fetch Time: " + d2.toLocaleTimeString();
const response = await fetch(api_url);
var data = await response.json();
// song info
var track = data["recenttracks"]["track"][0]["name"];
var artist = data["recenttracks"]["track"][0]["artist"]["#text"];
document.getElementById("demo2").innerText = "Fetched Data " . response;
}
myTimer();
get_data_from_api();
</script>
</body>
</html>
I added the 2nd timer to demonstratae that the code inside the funciton is indeed running.