0

Okay so I have these two badges: http://codepen.io/EagleJow/pen/bVrMZv

One is for a Twitch channel, one is for a Livestream channel. I'd like to know if there's an easy way to update the badges on the page every minute to show the current live status of the channels without reloading the rest of the page.

Here's the javascript for the Twitch one:

/*TWITCH BADGE*/
(function() {

  var user_name, twitch_widget;

  user_name = "nerdist";
  twitch_widget = $("#twitch-widget");

  twitch_widget.attr("href","http://twitch.tv/" + user_name + "/embed");

  $.getJSON('https://api.twitch.tv/kraken/streams/' + user_name + '?client_id=' + '&callback=?', function(data) {   
      if (data.stream) {
          twitch_widget.html("<span class='online'></span><strong> nerdist</strong></br><span class='live'>Online! Playing: " + data.stream.game + "</span>");
      } else {
          twitch_widget.html("<span class='offline'></span><strong> nerdist</strong></br><span class='notlive'>Offline</span>");
      }  
  });

})();

Any ideas?

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
Eagle Jow
  • 37
  • 1
  • 8

1 Answers1

1

You can use setInterval()

https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval

Example:

var updateBadge = function() {

  var user_name, twitch_widget;

  user_name = "nerdist";
  twitch_widget = $("#twitch-widget");

  twitch_widget.attr("href","http://twitch.tv/" + user_name + "/embed");

  $.getJSON('https://api.twitch.tv/kraken/streams/' + user_name + '?client_id=' + '&callback=?', function(data) {   
      if (data.stream) {
          twitch_widget.html("<span class='online'></span><strong> nerdist</strong></br><span class='live'>Online! Playing: " + data.stream.game + "</span>");
      } else {
          twitch_widget.html("<span class='offline'></span><strong> nerdist</strong></br><span class='notlive'>Offline</span>");
      }  
  });

}

setInterval(updateBadge, 60000);

updateBadge(); // Call function right now

(with help from Repeating setTimeout)

Community
  • 1
  • 1
Josiah Krutz
  • 957
  • 6
  • 16
  • Awesome! That works exactly how I need it to, except that it doesn't show the live status for the first minute. You can see what I mean here: http://codepen.io/EagleJow/pen/qOXKqa (I've set the interval to 6 seconds) – Eagle Jow Oct 13 '15 at 03:13
  • Though I suppose if I set the interval to 1 millisecond, it wouldn't be a problem and it would be even more accurate, but do you think it would be a problem for my site viewers if it's constantly reloading? Would that slow down the rest of the website? – Eagle Jow Oct 13 '15 at 03:17
  • Just call updateBadge() at the end. I updated the code. -- I wouldn't recommend refreshing every 1ms :-) Maaybe every second. Every five seconds might be reasonable. -- If you like my answer, feel free to mark as accepted! :-) – Josiah Krutz Oct 13 '15 at 03:48