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() {
$.ajax({
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(() => {
doThing();
}, 15000);
}
});
}
doThing();
So 15/30 seconds is better to space out your calls. And also deal with getting caching issues.
As
- 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