Shubham Shukla Shubham Shukla - 1 year ago 72
JSON Question

api calls are running unexpected number of times

i am working twitch tv api.api calls should me made equal to number of elemnts in streamer array.but it is call multiple times.u can see it on codepen.

jsfiddle link

javascript code

$(document).ready(function() {
var i;
var streamers = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; //streamers array
for (i = 0; i < streamers.length; i++) {
jsoncall(streamers[i]); //calling function for api calls.

function jsoncall(stream) { //function for api call
$.getJSON('' + stream + '?callback=?', function(data) {
if ( === null) { //if channel is offline display offline
$("p").append("<p>" + stream + " offline</p>");
} else { //if channel is online show what is he streaming.
$("p").append("<p>" + stream + + "</p>");

Answer Source

When you do this:


the content is appended to every <p> element on the page. Since you're adding more <p> elements in the content, you get duplicates all over the place.

Here's a forked version of your CodePen. I added an id to the main <p> element. Note that appending a <p> to a <p> doesn't really make sense anyway; <p> elements can't contain block-level elements like other <p> elements. Browsers allow it however. So, the HTML:

<p id=main></p>

And the updated JavaScript:

function jsoncall(stream) {
  $.getJSON('' + stream + '?callback=?', function(data) {
    if ( === null) {
      $("#main").append("<p>" + stream + "                                offline</p>");
    } else {
      $("#main").append("<p>" + stream + + "</p>");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download