title: Javascript function executes asynchronously, without me wanting it to
body: <p>I am making a navigation webapplication for a school project. It uses a program called "EasyStar" for the pathfinding. Because I need to calculate distances between some points pretty often, I decided to make a function for it:</p>
  
  <pre><code>function Distance(A, B, C, D, G) {
  easystar.setGrid(G);
  easystar.findPath(A, B, C, D, function( path ) {
  Dist = 1;
  for (F = 0; F &lt; Dist; F++){
  if (typeof path[F] !== "undefined"){Dist++;}
  else{}
  }});
  easystar.calculate();
  }
  </code></pre>
  
  <p>The problem I'm facing is that when I call the function, it finished after the next bit of code is executed: If I log Dist in the console both at the end of the function itself and right after the function is supposed to execute, it ends up with:</p>
  
  <pre><code>undefined
  [The actual distance]
  </code></pre>
  
  <p>If I do something like this</p>
  
  <pre><code>setTimeout(function(){console.log(Dist)},0.001)
  </code></pre>
  
  <p>or a 0.001 ms delay it does display it correctly, and I can start working with the value of Dist. The problem with that solution is that I can't keep that up for the entire document, as it would get really messy and I'm not even sure if it would work as a permanent solution.</p>