Search code examples
jquerygetjson

Pull for new results inside jQuery's getJSON


I'm working on adding a way to pull for results in my jQuery.JamCity.

Right now, it uses getJSON to pull api data from Last.Fm each $.each to parse through that data and output it.

I want to make it so that it checks for new results ever minute and IF there is a new item in data[0] to display it but ELSE, don't do anything because I don't want to just keep having the recent song pop-up.

How would I go about doing this? I imagine I use something like setInterval but I don't fully get how that works. Any code examples or ideas on how to achieve this functionality?


Solution

  • here is some starting code that would do this:

    var lastSong = null;
    var fetch = function(){
       $.getJSON('....', function(data) {
           if(data.length) {
               currentSong = data[0].some_unique_id
               if(lastSong != currentSong){
                  //put code here to play song
                  lastSong = currentSong;
               }
           }  
           setTimeout(fetch, 1000 * 60);
       });
    }
    fetch();