Learn how to use Dash Bio for next-gen sequencing & quality control. 🧬 Register for the Oct 27 webinar.

Leveraging Dcc.interval button starts callback but can't stop it

Hello,

I am new to dash/plotly/python. Worked quite diligently incorporate a much needed improvement in a graphing tool I am using however I wanted to stop the callback updates. I have tried the below code with success starting the callback, but it won’t stop it. Can someone please help me?

app.layout = html.Div(
    html.Div([
        html.Button(id='button', children='Enable dcc.Interval'),
        dcc.Graph(id='live-update-graph'),
        dcc.Interval(
            id='interval-component',
            interval=1*1000, # in milliseconds
            n_intervals=0,
            max_intervals=0,
        ),
    ])
)

## Callback to turn on interval, to trigger second callback.
@app.callback(
    Output(component_id='interval-component', component_property='max_intervals'),
   [Input(component_id='button', component_property='n_clicks_timestamp')]
)
def enable_interval_update(button):
    if not button:
        button = 0
        
    if button > 0:
        return -1 ## If button clicked, enabling interval component so it starts running.
    
    else:
        return 0
    
@app.callback(Output('live-update-graph', 'figure'),
              [Input('interval-component', 'n_intervals')])
def update_graph_live(n):
     some graphing function
     return fig

Here is the solution I came up with. Not sure why it required this much effort, maybe the team could look at incorporating some method to more easily allow start and stop scrolling for NRT like interval updates.

app = DjangoDash('NTSPlotly')
app.layout = html.Div(
    html.Div([
        html.Button(id='start', children='Enable Scroll'),
        html.Button(id='stop', children='Disable Scroll'),
        dcc.Graph(id='live-update-graph'),
        dcc.Interval(
            id='interval-component',
            interval=1*1000, # in milliseconds
            n_intervals=0,
            disabled=False,
        ),
    ])
)

## Callback to toggle interval
@app.callback(
    Output(component_id='interval-component', component_property='disabled'),
   [Input(component_id='start', component_property='n_clicks'), Input(component_id='stop', component_property='n_clicks')]
)
def toggle_interval_update(start, stop):
    ctx = dash.callback_context
    if not ctx.triggered:
        button_id = 'No clicks yet'
    else:
        button_id = ctx.triggered[0]['prop_id'].split('.')[0]
    
    if button_id == 'start':
        return False
    elif button_id == 'stop':
        return True
    
@app.callback(Output('live-update-graph', 'figure'),
              [Input('interval-component', 'n_intervals')])
def update_graph_live(n):

If someone has a better way let me know. Basically I mashed together examples I’ve found and got it to work.