I'm currently working for a school project where I'm working with the Spotify API. Now I've got so far that I receive the current song someone is listening to right now.
But the problem is, that information is only received once the site has been refreshed or opened, but I want it to keep refreshing every second (without refreshing the whole page) so it's up to date with the listener. Does anyone here have any idea on how I can accomplish that?
This is the AJAX request I'm using (I'm not sure if it's useful or anything)
$.ajax({
url: 'https://api.spotify.com/v1/me/player/currently-playing',
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(response) {
userInfoPlaceholder.innerHTML = userInfoTemplate(response);
console.log(response);
$('#login').hide();
$('#loggedin').show();
}
});
If there is any other code that I need to post in order to help, please let me know!
You can achieve this by using setTimeout or setInterval.
The difference is that setInterval executes given function again and again at the specified time intervals (until clearInterval() function is called); setTimeout executes given function one time just after the specified time interval.
After you complete the necessary process with the response. You can call makerequest() function recursively at the end of the function. The line includes comment provides makerequest() function to be called after 10s again.
function makerequest() {
$.ajax({
url: 'https://api.spotify.com/v1/me/player/currently-playing',
headers: {
'Authorization': 'Bearer ' + access_token
},
success: function(response) {
userInfoPlaceholder.innerHTML = userInfoTemplate(response);
console.log(response);
$('#login').hide();
$('#loggedin').show();
//process with the response and other stuffs
setTimeout(makerequest, 10000); //recursive call
}
});
}
You can set setInterval
. which will call a function in every defined seconds.
setInterval(function(){
callAjax();
}, 1000);
var callAjax = function(){
// Write you ajax here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With