Using dcc.Interval for continuous update

Hey @tbillah

I think the interval needs to be in the callback as an input. How about something like this:

import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html
from dash.exceptions import PreventUpdate

external_stylesheets = ["https://codepen.io/chriddyp/pen/bWLwgP.css"]

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(
    [
        "start value",
        dcc.Input(id="total", type="number", value=0),

        "countdown value", "  #can be hidden - or use dcc.Store instead
        dcc.Input(id="countdown", type="number", value=0, disabled=True),

        html.Div(id="page-content"),

        dcc.Interval(id="interval", n_intervals=0, interval=3000),
    ]
)


@app.callback(
    [Output("page-content", "children"), Output("countdown", "value")],
    [Input("total", "value"), Input("interval", "n_intervals")],
    [State("countdown", "value")],
)
def display_page(value, n, countdown):
    if not value:
        raise PreventUpdate

    ctx = dash.callback_context
    callback_input_id = ctx.triggered[0]["prop_id"].split(".")[0]

    if callback_input_id == "total":
        countdown = value
    elif countdown <= value and countdown >= 1:
        countdown -= 1

    output = html.Div([html.Plaintext(f"Value: {countdown}")])

    return output, countdown


if __name__ == "__main__":
    app.run_server(debug=True)

Edit: @Emil has a prettier counter :slight_smile:

2 Likes