title: How to start a counter for a setInterval
body: <p>I have this code working, but I'd like to improve it:</p>
  
  <pre><code>var c = canvas.getContext("2d"); 
  //this is called as an object method I created
  var animar = function () {
     var obj = this;//saves the object that called it to later access to its properties
     var counter= 0;
     var animacion = setInterval(function(){
              c.save()
              c.clearRect(0, 0, canvas.width, canvas.height);
              c.rotate(0.1*counter);
              obj.pintar();
              c.restore();
              counter++;
  
     }, 50);
  }
  </code></pre>
  
  <p>I'd like to use a outter function for posible future use but when I change the code I have, there is a hoisting problem and I don't know how to get  the counter inside the rotar() function without overwriting it all the time:</p>
  
  <pre><code>var animar = function () {
      var obj = this;
      var counter= 0;
      var animacion = setInterval(function(){
          rotar(obj)
      }, 50);
  }
  
  function rotar (obj) {
      c.save()
      c.clearRect(0, 0, canvas.width, canvas.height);
      c.rotate(0.1*counter);
      obj.pintar();
      c.restore();
      counter++;
  }
  </code></pre>
  
  <p>I get that the first one works because they are nested, while in the second example isn't. How can I have a counter for the setInterval <strong>WITHOUT USING A GLOBAL VARIABLE</strong>?
  (I mean... if I call it a second time, it will not start in 0. If I set it to be 0 in the animar() function, it would work, but then I'd need to set it to 0 in every function that uses a counter or using counters with diferent names. This two posibilities don't sound good.)
  Thanks</p>