Execute a code when detecting livestream

Hello everybody. I’ve created a javascript code that detects when I’m going live on Twitch. However, it sometimes execute more than once and I want it to execute only once when it detects my stream. My actual code is this.
I’m using the variable “executed” to handle this, but I don’t know if I’m doing it the correct way.
I would appreciate indications to achieve this, thanks!

Change the code to not use setInterval

If a call takes too long to run your calls collide with each other and you have more than one call running.

Also generally calling every 2 seconds is bad as the data will only change once a minuite.

So, the following is a potential fix

var executed = false;

function doThing() {
    type: 'GET',
    url: 'https://api.twitch.tv/helix/streams?user_login=username',
    dataType: 'json',
    headers: {
      'Client-Id': 'clientid',
      'Authorization': 'token'
    success: function(channel) {
      if (channel.data.length == 0) {
        executed = false;
      } else {
        if (!executed) {
          //do stuff
          executed = true;
      // setup to check again in 15 seconds
      // and after this loop has finished processing.
      setTimeout(() => {
      }, 15000);


So 15/30 seconds is better to space out your calls. And also deal with getting caching issues.


  • call one could see offline
  • call two sees online
  • call three sees offline (but you are really live)
  • call four sees online

Call three is in error due to caching by the API as you are hammering too quick

You may also be interested in EventSub instead http://dev.twitch.tv/docs/eventsub where Twitch will tell you when the stream goes live/offline rather than having to poll continually

1 Like

Oh I see!
About the seconds thing, I just forgot a 0 in the pastebin code haha, currently I was calling it every 20 seconds.
Thank you so much for your response, I will try it.

Yeah even with 20 seconds, your code from pastebin doesn’t look and see if a previous request is still running.

So you either have multiple requests crashing into each other, or getting hits on different servers in the API pool and having a caching. But it’s more likely the former.

If you are doing one per 20 seconds then you ajax call could be extended to terminate after 15 seconds if it takes too long to run.

Yeah, I will definitely replace the setInterval function and terminate the request if it takes too long, thanks

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.