Search code examples
javascriptspotify

I'm getting data from the Spotify API, but after a while running it marks an error and starts logging the same information over and over


I'm trying to understand Spotify API. This small code console logs the information of the current beat of the song that the user is listening to.

It works fine but after a few seconds running, it logs an error and after that error it starts logging the information of the same beat over and over again. Any ideas? Here is my code and thank you in advance!

var spotifyApi, spotifyToken;
var current, currentId, timeProgress, beatStart, beatsTotal;
var dataArray = [];
var beatsArray = [];
var spotifyToken = 'token';
spotifyApi = new SpotifyWebApi();
spotifyApi.setAccessToken( spotifyToken );

init();

function init(){
  onReceiveCurrent();
}

function onReceiveCurrent ( err, data ) {
  if (err) {
    console.error(err);
    return;
  }

  spotifyApi.getMyCurrentPlaybackState({}, onReceiveCurrent );
  currentId = data.item.id;
  timeProgress = data.progress_ms;
  spotifyApi.getAudioAnalysisForTrack(currentId, onReceiveAnalysisCallback);
}

function onReceiveAnalysisCallback ( err, data ) {
  if (err) {
    console.error(err);
    return;
  }

  for (var i=0; i<data.beats.length; i++) {
    beatsArray[i] = data.beats[i].start;
  }

  var found = beatsArray.find(function (element) {
        return element >= timeProgress/1000;
  });

  var a = beatsArray.indexOf(found);
  beatStart = data.beats[a];
  console.log(beatStart);
}

Here's the error:

enter image description here


Solution

  • You've accidentally created an infinite loop in the onReceiveCurrent method, which calls getMyCurrentPlaybackState which has a callback of onReceiveCurrent. It's calling itself over and over until it hits Spotify's limit and returns a 429.

    The callback should be a separate function like so:

    function callSpotify () {
      spotifyApi.getMyCurrentPlaybackState({}, onReceiveStateCallback );
    }
    
    function onReceiveStateCallback(err, data) {
      if (err) {
        console.error(err);
        return;
      }
    
      currentId = data.item.id;
      timeProgress = data.progress_ms;
      spotifyApi.getAudioAnalysisForTrack(currentId, onReceiveAnalysisCallback);
    }