Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read the contents of a text file every 15 seconds

I'm working on a music site: I have a text file on the server which contains the name of the currently playing song. I would like read the text file every fifteeen seconds, and change the text displayed on my site, without a refresh.

Now, using a little jQuery and javascript, I have actually gotten to the point where the file is read and displayed the first time, but it wont refresh . I have attempted all sorts of setInterval functions, but for the life of me I cant get this part to work. Any help would be greatly appreciated.

Here is what I have:

<script type="text/javascript"> 
$(document).ready(function() {
    jQuery.get('http://www.XXXXX.com/nowplaying/NowPlaying.txt', function(data) {
        var myvar = data;
        var parts = myvar.split(/\n/);
        var songtitle = parts[0];
        var songartist = parts[1];
        var songalbum = parts[2];
        var songtime = parts[3];
        $('#songtitleholder').html(songtitle);
        $('#songartistholder').html(songartist);
        $('#songalbumholder').html(songalbum);
    });
});​
</script>
like image 844
Richard Taylor Avatar asked Dec 22 '12 16:12

Richard Taylor


1 Answers

You can put the code you want to execute repeatedly in function and pass that function in setTimeout. The second parameter of setTimeout will take interval in millisecond.

Using setTimeout here IMO is more appropriate here as It will exclude the time taken for send request and receiving response. It will send request every 5 second after receiving response.

<script type="text/javascript"> 

 $(document).ready(function() {

    function functionToLoadFile(){
      jQuery.get('http://www.XXXXX.com/nowplaying/NowPlaying.txt', function(data) {
       var myvar = data;
       var parts = myvar.split(/\n/);
       var songtitle = parts[0];
       var songartist = parts[1];
       var songalbum = parts[2];
       var songtime = parts[3];

       $('#songtitleholder').html(songtitle);
       $('#songartistholder').html(songartist);
       $('#songalbumholder').html(songalbum);
       setTimeout(functionToLoadFile, 5000);
    });
    }

    setTimeout(functionToLoadFile, 10);
});

</script>
like image 117
Adil Avatar answered Nov 15 '22 20:11

Adil