Close

Added a timer

A project log for Skull Counter using API

Display number of skulls for any project on an external website.

alex-richAlex Rich 05/07/2015 at 00:440 Comments

Ok, I initially had this setup so the skull counter would only refresh its value on page load. After thinking about it I realized most people will expect to see this timer update without a page refresh so I decided to implement an ajax timer. First I use the jquery document ready shorthand to load a function called getskulls:

$(function() {
  
    getskulls();
  
  }); // end $(

then I made a getskulls function with a timer at the end that calls itself every 10 seconds.
function getskulls() {
  
    $.get("skullcount/return_skulls.php", function(result) {
    
      $('#skullcounter span').html(result);
      
    }) // end $.get(
    
    .done(function() { // chain this to the end of the $.get( function to restart the getskulls function on a timer
    
      setTimeout(getskulls, 10000); // refresh value every 10 seconds
      
    }); // end .done(
    
  } // end getskulls()
this function makes a get request to my php file which handles the API calls. I have the php file set to only make API requests for "fresh" skull counts every 30 seconds, otherwise it uses a cached value. This is to handle a situation where the site gets a spike in views and say 20 people are viewing the page at one time. In this instance, the skull value will be pulled from the API and cached every 30 seconds and each viewer will have the most up to date skull count within 10 seconds of the cache being updated. I confused myself when choosing these timer values, someone tell me if that makes any sense.

Discussions