How to use a checkbox to toggle automatic page refresh every 1 second in Streamlit?

Hi everyone,

I’m trying to implement a feature in Streamlit where a checkbox allows the user to toggle automatic page refresh every 1 second on or off.

The idea is:

  • When the checkbox is checked, the page should automatically refresh every 5 seconds.
  • When the checkbox is unchecked, the page should stop refreshing.

I’m not sure about the correct structure for implementing this behavior.

Could someone please show me a minimal working example or point me in the right direction? Thank you!

I tried the following code, but I found that the time starts auto-refreshing as soon as I open the page, even though I haven’t clicked the checkbox. Could you please help me identify what’s going wrong? Thank you.

import streamlit as st
import time

st.title("Streamlit Auto-Refresh Example")

auto = st.checkbox("Enable auto-refresh (every 1 second)", key="auto_refresh")

run_interval = 1 if auto else None

@st.fragment(run_every=run_interval)
def refreshing_fragment():
    st.write("Current time:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

refreshing_fragment()