I have an API data source (JSON) that yields 12 new results every 60 seconds. The client wants a little pop-up to show up in the bottom corner of their website saying "UserX just earned $y from their app." They want to use real data from the API, and they want the results to be shown on a semi-random basis, so it looks "natural".
So - basically every 60 seconds, I want to call the API to get a new set of 12 records... and in the 60 seconds that follow, cycle through the 12 records that I got in random intervals (between 3 - 7 seconds).
Here is my code thus far:
$(document).ready(function(){
function gatherData() {
$.ajax({
dataType: "json",
url: "https://www.somesite.com/api-endpoint",
success: function(data) {
loopThroughData(data, 0);
}
});
}
function loopThroughData(data, i) {
var randomTime = Math.floor(Math.random() * (Math.floor(7000) - Math.ceil(3000)) + Math.ceil(3000));
setTimeout(function(){
var rewardString = name + " just earned "+data.currency+" " + data.currency_name + "s and $"+data.dollar_amount+" for the "+data.platform+". <span>"+data.location+" - A few seconds ago</span>";
$("#reward-body").empty().append(rewardString);
$("#reward-notification").fadeIn('slow').delay(3000).fadeOut('slow');
i++;
if (i < 12) {
loopThroughData(data, i);
}
}, randomTime);
}
var outerLoop = setInterval(gatherData(), 60000);
});
With this code, it does indeed call the data source, and cycles through the results in random intervals. However, once it gets through the initial 12 results, it does not call the data source again. So, it appears as though my setInterval isn't working. I attempted this both with the defining variable (var = outerLoop), as well as without it, but that doesn't seem to make a difference. I also adjusted the 60000 ms time to 6000 just to see if it calls the gatherData() function more than once. It does not.
You can see this all in action here: https://codepen.io/johnhubler/pen/YzqGrGz
Does using setTimeout negate setInterval, or am I just missing something silly? Any help would be appreciated!