How can I make this function execute in the background?

Hi everyone, I would like to let this function run in the background so that I can make the website do other stuff while this timer goes:

import streamlit as st
import asyncio

async def time_convert():
    container = st.empty()
    container_2 = st.empty()
    button_start = container_2.button('Start')
    clock = f"{0:02d}:{0:02d}"
    if button_start:
        button_end = container_2.button('End')
        for secs in range(0, 1000, 1):
            mm, ss = secs // 60, secs % 60
            container.metric("Time Lapsed", f"{mm:02d}:{ss:02d}")
            r = await asyncio.sleep(1)
        if button_end:
            container_2.empty()
            button_start = container_2.button('Start')

    else:
        container.metric("Time Lapsed", clock)

asyncio.run(time_convert())
if st.button("hi"):
    st.write("Hello")

As you can see, I can’t click the button while the function is executing. Am I missing something?

Thanks in advance! :innocent:

Hi @ettorecarlessi,

Thanks for posting!

Streamlit’s core execution model results in the app being rerun anytime someone interacts with a widget (in this case, clicks the button).

To prevent the page from re-running when someone clicks a button/interacts with a widget, you can set up the app as a form with a submit button (the app wouldn’t re-run until the user hits submit). Can you share a little more about the use case? What happens after the user clicks the button?

Caroline :balloon:

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.