title: Javascript - getting return value for setTimeout in recursive function
body: <p>I have a recursive function which contains some drawing code inside.  I was advised to use setTimeout as my drawing was not being displayed until the end of exection.  First I put just the drawing code inside setTimeout but this did not help, however when I put the main recursive loop inside setTimeout the drawing worked perfectly, as shown below.</p>
  
  <p>However I need to use the return value of setTimeout (i.e. <code>state</code> as shown below).  How can I get this return value when using setTimeout, or solve this problem in another way.</p>
  
  <pre><code>var doLearning = function(time, observedData, state, domain, sampleAction, selectModel, numSamples, depth, discount, stateQueries) {
      if(stateQueries[0](time, state) === true) {
          console.log("New Round");
          var currentModel = selectModel(observedData, 10, stateQueries);
          var bestAction = sparseSampleMcmc(depth, numSamples, discount, currentModel, state, sampleAction, stateQueries);
          var newStateReward = domain.executeAction(bestAction, stateQueries);
          observedData.push(bestAction, newStateReward[1], newStateReward[0]);
          console.log(time);
          setTimeout(doLearning, 100, time + 1, observedData, newStateReward[0], domain, sampleAction, selectModel, numSamples, depth, discount, stateQueries);
      } else {
          console.log("Game Over");
          return state;
      }
  }
  </code></pre>