I have some elements in my page and I need to refresh their contents every 5 seconds. The code that I'm going to show you works well but it looks so long and repeating itself. When I use only setInterval function, page doesn't loaded regularly before the interval comes. Can you suggest a better way to do this? Thanks in advance. Here is my code:
var $song=$(".song");
var $album=$(".album");
var $cover=$(".cover");
var $background=$(".overlay-bg");
$.ajax({
url: "song.php",
success: function (response) {
var nowPlaying=$.parseJSON(response);
$song.html(nowPlaying.song);
$album.html(nowPlaying.album);
$cover.css("background-image", "url("+nowPlaying.cover+")");
$background.css("background-image", "url("+nowPlaying.cover+")");
}
})
var refreshSongDetails=setInterval(function() {
$.ajax({
url: "song.php",
success: function (response) {
var nowPlaying=$.parseJSON(response);
$song.html(nowPlaying.song);
$album.html(nowPlaying.album);
$cover.css("background-image", "url("+nowPlaying.cover+")");
$background.css("background-image", "url("+nowPlaying.cover+")");
}
})
}, 5000);
Create your ajax call into a function and call it :
var $song=$(".song");
var $album=$(".album");
var $cover=$(".cover");
var $background=$(".overlay-bg");
function ajaxCall() {
$.ajax({
url: "song.php",
success: function (response) {
var nowPlaying=$.parseJSON(response);
$song.html(nowPlaying.song);
$album.html(nowPlaying.album);
$cover.css("background-image", "url("+nowPlaying.cover+")");
$background.css("background-image", "url("+nowPlaying.cover+")");
}
})
}
ajaxCall();
var refreshSongDetails = setInterval(ajaxCall, 5000);
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