1👍
✅
One simple way to do this is via ajax. Using javascript make a call to your method every second and display the response.
In this case you probably don’t need a loop on the server side and can just return the state… If the server is started, display the appropriate text, if it is not show the countdown.
The JavaScript code will be something like this
var i = 10;
var timer = window.setInterval(function(){
$.ajax({
url: // your url
data: // any parameters you need to pass as JSON
success: function(response){
if (response == 'started'){
$('#server_status').text('Wait for ' + i + ' seconds')
i--;
}else
$('#server_status').text('running')
}});
if (i == 0)
window.clearInterval(timer);
}, 1000); // Repeat every 1 second
Please note that I have used JQuery for the ajax call
The other way might be to use a StreamingHttpResponse
In this case your loop should be separated into a method and the returned value should be sent to the html page or as the response
def count_seconds():
for i in range (10,0,-1):
time.sleep(1)
yield 'Wait for %d seconds \r' % i,
The yield
keyword will return the ith value every time the function is called.
Source:stackexchange.com