Removing setInterval

The above code has this added to it:

Init Function

function init(opts) {
    loadPlayer();
    if (apiIsReady) {
      addVideo(opts.video, opts.playerVars || {});
    }
    else
    {
      waitting_inits.push(opts)
    }
}

CallBack Function

window.onYouTubePlayerAPIReady = function() {
  apiIsReady = true;
  load_all_waitting_inits()
};


var waitting_inits=[];
function load_all_waitting_inits()
{
    for(var opts of waitting_inits)
  {
    init(opts);
  }
}

Yes, that also waits until the time is right for those inits to occur. That is a good way of doing things too, and is preferable to using setInterval.

If I remove this line from the code, the browser freezes.
apiIsReady = true;

How would that be fixed?

Remove this line from the code.
apiIsReady = true;

Then try clicking on the image.

That’s why I thought it was a bad code.

Do you see what I mean?

You can get rid of apiIsReady completely.

Where it was used in the if statement, just check for YT instead. That’s the youtube api.

Could you re-write these parts so it’s better written?

I don’t want the browser to keep freezing on me.

Init Function

function init(opts) {
    loadPlayer();
    if (apiIsReady) {
      addVideo(opts.video, opts.playerVars || {});
    }
    else
    {
      waitting_inits.push(opts)
    }
}

CallBack Function

window.onYouTubePlayerAPIReady = function() {
  apiIsReady = true;
  load_all_waitting_inits()
};


var waitting_inits=[];
function load_all_waitting_inits()
{
    for(var opts of waitting_inits)
  {
    init(opts);
  }
}

See above about apiIsReady.

Also, waitting_inits.forEach(init);

I’m not touching the jsfiddle though.
When I get it right on here, you can share it with me.

const waitting_inits=[];
function load_all_waitting_inits()
{
    waitting_inits.forEach(init);
  {
    init(opts);
  }
}

I don’t understand how removing a piece of javascript from a code can make your browser freeze. It froze my whole pc.

All of this can be deleted then, right?

  let apiIsReady = false;
    let timer;
    window.onYouTubePlayerAPIReady = function() {
        apiIsReady = true;
    };

The code works with all of that removed:

1 Like

@Paul_Wilkins

All of this occurs after clicking on 1 video box.
Does that make logical sense?

@Paul_Wilkins

That even happens with the, setInterval Code.

That can’t be good.

Yes, that makes sense.

Why, can you explain?

It’s the youtube API that’s doing those things to load the video.

Over 50 domains loading?

After 1 video box is clicked.

That’s how the sausage is made.

1 Like

Over 64 requests after 1 video is clicked?

That’s insane.

Welcome to YouTube.

Just this gets 30 + requests.

<iframe width="198" height="198" src="https://www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>