title: How to make Javascript execute a code every x seconds, but make it wait before a function was fully executed?
body: <p>Here I have a piece of code that auto-executes every 2 seconds. However, the time it takes to execute function roll() varies due to the Internet connection's peaks and bottoms. I'm trying to make the function roll() execute itself automatically every 2 seconds, but the code must wait till the function is fully executed before proceeding and auto-executing again.</p>
  
  <p>P.S. Any  suggestions of a better title for this question would be appreciated.</p>
  
  <pre><code>var init = 0.01
  
  var start = init
  var $odds = $("#oddsOverUnder")
  var $button = $("#roll")
  var $bet = $("#bet")
  
  function roll() {
      $bet.val(start)
      $button.click()
      setTimeout(function() {
          var tr = document.querySelector("#myBetsTable tr:nth-child(2)")
          var cls = tr.getAttribute('class')
          if (cls === 'success'){
              start = init
              $bet.val(start)}
          else{
              start = start * 2
              $bet.val(start)
              $odds.click()}
              $button.click();
      setTimeout(function() {
              $button.click();
              },1000);
              },1000);
  }
  
  setInterval(roll, 2000)
  </code></pre>