Black Lives Matter. Please consider donating to Black Girls Code today.

How to reset n_intervals in dcc.Interval?

I am animating a slider in dash and would like it to have the option of restarting from any point in the slider

Layout snippet:

html.Div([
dcc.RadioItems(id=‘speed-selection’,
value=60 * 60 * 1000,
options=[
{‘label’: ‘PLAY’, ‘value’: 2000},
{‘label’: ‘PAUSE’, ‘value’: 60 * 60 * 1000}, # or just every hour
{‘label’: ‘PLAY AT REDUCED SPEED’, ‘value’: 5000},
{‘label’: ‘FAST FORWARD’, ‘value’: 1000}
]
),
dcc.Interval(id=‘animator’,
interval=1 * 1000, # in milliseconds
n_intervals = 0,
),
dcc.Slider(id=‘slider’,
min=1,
max=5,
value=1,
marks = {1:1, 2:2, 3:3, 4:4, 5:5},
step=1
),
html.Button(‘CLEAR’, id=‘reset-animator’),`

Callbacks snippet:

@app.callback(
dash.dependencies.Output(‘animator’, ‘interval’),
[dash.dependencies.Input(‘speed-selection’, ‘value’)])
def update_interval(value):
return value

@app.callback(
dash.dependencies.Output(‘slider’, ‘value’),
[dash.dependencies.Input(‘animator’, ‘n_intervals’),
dash.dependencies.Input(‘clear-1’, ‘n_clicks’)])
def on_click(n_intervals, n_clicks):
if n_intervals > 4:
return 0
else:
return (n_intervals+1) % 5

The value of n_interval is used to select the next new data point to plot, so when i need to restart the animation from a previous point, I need to change the n_interval to a previous value based on user selection in slider or atleast just reset it back to 0 (by click of a button). I tried to use a callback thats sets n_intervals = 0 when a button - ‘reset-animator’ is clicked but that didnt work

You can try putting the interval in a div and remount the component by using a children output callback with the dcc.Interval ?

can you explain how will i reset the n_intervals if it exceeds say 20 in following example?

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

app = dash.Dash()
app.scripts.config.serve_locally = True

app.layout = html.Div([
html.Div(id=‘my-output-interval’),
dcc.Interval(id=‘my-interval’, interval=1000),
])

@app.callback(
Output(‘my-output-interval’, ‘children’),
[Input(‘my-interval’, ‘n_intervals’)])
def display_output(n):
return ‘{} have passed’.format(n)

if name == ‘main’:
app.run_server(debug=True)

I am not sure if I understand your question.

If you need to reset when the counter exceeds a particular value, you can use a modulus operator, i.e idx = n_intervals % particular_value.

If you need to reset when a user clicks, you could subtract the current value (of n_intervals). This value would then have to be stored somewhere (a hidden div, a server cache, etc.).

Thanks a lot for pointing out the modulus operator. That seems to be the most elegant way.