lrhorer
lrhorer

Reputation: 385

How can I create a web page with a countdown timer in Python3?

I need to create a web page with a countdown timer. The below doesn't work, because the web page halts until after the countdown completes. It doesn't update the page every second, and it also does not place the values in the properly. It scrolls them. How can I get this to work? Alternately, I believe I could embed javascript into the Python code, but I have not firgured out how to do this. Everything I have fund in the web concerning calling a javascript from Python seems very arcane, and I can't figure it out, at all.

index.html:

div.Countdown {
    position: fixed;
    top: 26;
    left: 480;
    width: 300px;
    font: bold 24px Arial;
    color: black;
}
</STYLE>

index.cgi:

import time

print( '</b></h2></table></p>')
def countdown(t):
    while t:
        mins, secs = divmod(t, 60)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        print( '<div id="Countdown">')
        print(timeformat, flush=True)
        print('</div>')
        time.sleep(1)
        t -= 1
    print('Goodbye!\n\n\n\n\n')


countdown(4)

print( '</BODY>')
print( '</HTML>')```

Upvotes: 1

Views: 1796

Answers (1)

Maus
Maus

Reputation: 1843

You've missed something fundamental about the way the web works-- there's a client and a server. Usually but not always, the client is running on a different machine than the server. In conventional contexts, the client submits a request to the server, to which the server responds. The client waits until the server has finished responding before it attempts to render the response.

The issue you are running into is that your HTML isn't finished rendering until your while loop has completed, so the client won't render anything until your timer has reached zero.

I wouldn't recommend accomplishing this task in python at all, which only runs on the server. It's literally possible but only by very convoluted means. I would instead use a different language called javascript which runs on the client. If you're using chrome you can right click this web page, and select the "inspect" option:

enter image description here

Once there you can experiment with JavaScript by selecting the console option from the top of the developer console.

This looks like an tutorial on how to create a timer at an appropriate level for someone starting out: https://www.geeksforgeeks.org/create-countdown-timer-using-javascript/

Upvotes: 1

Related Questions