title: Running ajax on page load and then every 5 seconds
body: <p>I still find it hard to grasp some of the javascript/jquery concepts.</p>
  
  <p>I wanted to find a way of loading ajax on page load and then every 10 seconds after that. I stumbled upon <a href="http://www.erichynds.com/blog/a-recursive-settimeout-pattern" rel="nofollow">http://www.erichynds.com/blog/a-recursive-settimeout-pattern</a> which suggested is a good idea as it provided some error detection to stop script running if ajax fails, only problem is that on page load, it must wait 5 seconds before requesting data, I want it to request data every 10 seconds, as well as on page load, so I don't have to wait 10 seconds before seeing anything. </p>
  
  <p>How do I get it to load on page load aswel as every 10 seconds after that?</p>
  
  <p>I tried adding the following:</p>
  
  <pre><code>   if(this.success_count&amp;&amp;this.failed == 0)
      {
          jQuery.proxy(this.getData, this)
      }else{
          setTimeout(
             jQuery.proxy(this.getData, this),
             this.interval
          );
      }
  </code></pre>
  
  <p>To this:</p>
  
  <pre><code>    var poller = {
  
          failed: 0,
          success_count: 0,
  
          interval: 10000,
  
          init: function(){
  
             if(this.success_count&amp;&amp;this.failed == 0)
              {
                  jQuery.proxy(this.getData, this)
              }else{
                  setTimeout(
                     jQuery.proxy(this.getData, this),
                     this.interval
                  );
              }
           },
  
         getData: function(){
             var self = this;
  
             jQuery.ajax({
                 url        : "foo.htm",
                 success    : jQuery.proxy(self.successHandler, self),
                 error    : jQuery.proxy(self.errorHandler, self)
             });
         },
  
          // =&gt; Handle Success
          successHandler : function( response ){
  
                if( response === "failure" ){
                    this.errorHandler();
                } else {
                  ++this.success_count;
                    this.init();
                }
            },
  
         errorHandler: function(){
             if( ++this.failed &lt; 5 ){
                this.interval += 1000;
                this.init();
             }
         }
      };
  
  poller.init();
  </code></pre>
  
  <p>I then also tried this, but it requests the data twice, understandably once for each.</p>
  
  <pre><code>poller.getData();
  poller.init();
  </code></pre>