title: Flask Countdown Timer
body: <p>I am building a game using Flask where every round has a countdown time to complete the round. I want the time value to decrease by 1 every second and to update without reloading the page. The countdown itself uses a time.sleep to wait 1 second before setting the next value of a generator to a global variable, which is passed through jsonify to my HTML. However it is not working. Any help would be appreciated!</p>
  <p>python:</p>
  <pre><code>def countdownGen(t):
      return (t-i for i in range(t))
  
  def countdown(t):
      gen = countdownGen(t)
      while t &gt; 0:
          try:
              globaltimer = next(gen)
              time.sleep(1)
          except StopIteration:
              globaltimer = 0
  
  @app.route('/_timer', methods=['GET'])
  def timer():
      global globaltimer
      globaltimer = 60
      countdown(globaltimer)
      return jsonify(result=globaltimer)
  </code></pre>
  <p>HTML / JS:</p>
  <pre><code>&lt;script type=&quot;text/javascript&quot;&gt;
    var intervalID = setInterval(update_values,1000);
    $SCRIPT_ROOT = {{request.script_root|tojson|safe}};
    function update_values() {
      $.getJSON($SCRIPT_ROOT + '/_timer',
      function(data) {
        $('#result').text(data.result);
      });
    };
  &lt;/script&gt;
  
  &lt;body onload=&quot;update_values();&quot;&gt;
    &lt;span id=&quot;result&quot;&gt;?&lt;/span&gt;
  &lt;script&gt;
  document.getElementById(&quot;result&quot;).innerHTML;
  &lt;/script&gt;
  &lt;/body&gt;
  </code></pre>