Can I detect a file change without an infinite interval or page reload?

My problem is basically this: I have a web page with an online radio on another subdomain (source of airtime). Now I realized that this radio plugin has a nice real-time API, so I can access the information about the previous, current and next track (and show) in JSON at this URL: http://music.wickedradionet.com / api / live-info .

I need to show this information on a web page. I can make it work with javascript interval, updating the information from the API URL every second (or every 5 seconds, it doesn't matter), but I think there should be a better way to do this.

Is there a way to check if the file has been modified and update the information only if they do not match? I think that this can be done using some kind of complex PHP, for example, creating a CRON job or, possibly, using a WebSocket application. Any better way than checking it in a JS interval?

The javascript I'm using now for the update is: http://wickedradionet.com/js/wickedradio-playlist.js

+4
source share
2 answers

Two ways to improve your survey are described below:

1) More effective AJAX polling

, ajax ( , ), , . $.ajax() complete. timeout (.. 30 ) , , , - .

(function betterPoll(){
    $.ajax({ url: 'http://music.wickedradionet.com/api/live-info/', success: function (data) {
        // do something with "data"
    }, dataType: "json", complete: betterPoll, timeout: 30000 });
})();

2) WebSocket

WebSocket. , " ".

Node.js, docs , Socket.IO WebSocket. PHP, Ratchet PHP WebSockets.

Socket.IO:

HTML:

<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script src="example.js"></script>

"example.js" - :

var socket = io.connect('http://music.wickedradionet.com/api/live-info/');
socket.on('an event', function (data) {
  // do something with "data"
  socket.emit('another event', { other: 'data' });
});

- .on('another event', function () {}) .emit('an event', function () {}).

+4

, , . , , , .

function stringToDate(s)  {
	s = s.split(/[-: ]/);
	return new Date(s[0], s[1]-1, s[2], s[3], s[4], s[5]*1);
};
function getPlaylistData() {
	$.ajax({
		dataType: "jsonp",
		url: "http://music.wickedradionet.com/api/live-info/",
		success: function (result) {
			/* Change your DOM, than calculate time for next request this way: */
			var requestTime = stringToDate( result.schedulerTime ).getTime() - result.timezoneOffset*1000;
			var nextChange = stringToDate( result.next.starts ).getTime();
			var differenceInMiliseconds = nextChange-requestTime;
			console.log( differenceInMiliseconds );
			setTimeout(getPlaylistData, differenceInMiliseconds);
		}
	});
};
$(document).on('ready', function () {
    getPlaylistData();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Hide result
+1

Source: https://habr.com/ru/post/1584419/


All Articles