title: javascript - recursive function & setTimeout
body: <p>I am trying to write a javascript function that when called performs function DoSomething() once,
  but can be triggered to perform the function repeatedly until triggered to stop.</p>
  
  <p>I am using setTimeout() function. I am not sure if this is best method from performance and memory point of view.
  Also I would like to avoid global variable if possible</p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  &lt;html&gt;
      &lt;script src="jquery.js"&gt;&lt;/script&gt;
  
      &lt;script&gt;
      var globalCheckInventory = false;
  
      $(document).ready(function(){
          // start checking inventory
          globalCheckInventory = true;                 
          myTimerFunction();  
      }); 
  
      // check inventory at regular intervals, until condition is met in DoSomething
      function myTimerFunction(){
          DoSomething();
          if (globalCheckInventory == true)
          {
              setTimeout(myTimerFunction, 5000);      
          }           
      }
  
      // when condition is met stop checking inventory
      function DoSomething() {     
          alert("got here 1 ");
          var condition = 1;
          var state = 2 ;
          if (condition == state)
          {
              globalCheckInventory = false;
          }        
      }
      &lt;/script&gt;
  </code></pre>