Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dash - Interval not invoking callback

I'm using Dash - Plot.ly to create a dashboard and I need a periodic update. I found the dcc.Interval() component that should do the job but there's a strange behavior happening. In case of correct code, the callback is invoked only once, in case there's an error in the code like referencing an inexistent variable, the cyclic behavior shows up. Any idea on what might be wrong?

import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly
from dash.dependencies import Input, Output

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

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.layout=html.Div([dcc.Interval(id='interval-component',
                         interval=1*1000, n_intervals=0)], id="acoolId")


@app.callback(
    Output('acoolId', 'children'),
    [Input('interval-component', 'n_intervals')])
def timer(n):
    # print(asdlol) # if this line is enabled, the periodic behavior happens
    return [html.P("ASD " + str(n))]


if __name__ == '__main__':
    app.run_server(debug=True)
like image 821
Alessandro Gaballo Avatar asked Feb 25 '26 16:02

Alessandro Gaballo


1 Answers

The problem is that your callback is replacing the children of the element with the ID "acoolID", and that is where your interval component is. So, the callback fires once, and replaces the input to the callback, making it impossible to fire again.

Change your layout to something like this, so that the children you update is a different component:

app.layout = html.Div(
    children=[
        dcc.Interval(id='interval-component', 
                     interval=1 * 1000, 
                     n_intervals=0),
        html.Div(id="acoolId", children=[]),
    ]
)

I've tested this, and the callback now works properly.

like image 94
coralvanda Avatar answered Feb 27 '26 04:02

coralvanda