How to do an slider that automatically increase its value after a time interval? (Session state understanding problem)

i want to do an slide in streamlitr where the user can manually select an value and have a button to let the computer automatic increase this value (say, increase by +1 every second).
I managed to create a slider that can be manipulated directly by the user or by a “previous” and “next” button.
But i fail to understand how to create a button that toggles the “autoplay” variable (between True and False)
The button that i made seems not to work at all (autoplay does not change its value)

import streamlit as st

MAX_LINES = 1000
MIN_LINES = 0

st.session_state["autoplay"] = False

def next_line():
    if st.session_state["slider1"] < MAX_LINES:
        st.session_state["slider1"] += 1
    else:
        pass # todo: warning end of slider reached
    return

def prev_line():
    if st.session_state["slider1"] > MIN_LINES:
        st.session_state["slider1"] -= 1
    else:
        pass # todo: warning start of slider reached
    return


def autoplay_clicked():
    st.session_state["autoplay"] = not st.session_state["autoplay"]
    #st.write(st.session_state["autoplay"])

line_number = st.slider("line number", min_value=MIN_LINES, max_value=MAX_LINES, key="slider1")
col1, col2,col3,col4 = st.columns(4)
with col1:
    st.write("selected line number:", line_number)
with col2:
    button_prev = st.button("prev", on_click=prev_line, key="button_prev")
with col3:
    button_next = st.button("next", on_click=next_line, key="button_next")
with col4:
    button_autoplay = st.button("autoplay", on_click=autoplay_clicked, key="autoplaybutton")
    st.write(st.session_state["autoplay"])

That is because line 6:

st.session_state["autoplay"] = False

The button actually works, but then in the next rerun autoplay is set to False.

You can fix this by doing:

if "autoplay" not in st.session_state:
    st.session_state["autoplay"] = False

This will make sure that it only sets the default value the first time you run the app, not every time it gets rerun.