title: Trigger function and open URL at the same time
body: <p>I am creating a counter which counts the number of clicks made to an anchor tag. I also need the URL to be opened at the same time. I tried the below code. The page is redirected before the function executes.</p>
  
  <p>Is there a better way to do this?</p>
  
  <p>Code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () {
   var $res = $('#counter').text($.cookie('link-count') || 0)
      
      $('a').click(function () {
          var count = parseInt($.cookie('link-count'), 10) || 0;
  
          count++;
          if (count &gt; 10) {
              $(this).attr("href", "https://www.yahoo.com");
          }
          $.cookie('link-count', count);
          $res.text(count);
          location.href = $(this).attr("href");
          
      });
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;a href="www.google.com"&gt;Google&lt;/a&gt;
  &lt;div id="counter"&gt;0&lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>