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!
python:
def countdownGen(t):
return (t-i for i in range(t))
def countdown(t):
gen = countdownGen(t)
while t > 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)
HTML / JS:
<script type="text/javascript">
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);
});
};
</script>
<body onload="update_values();">
<span id="result">?</span>
<script>
document.getElementById("result").innerHTML;
</script>
</body>