Dash Events trigger callback function Twice in every single event

Dash Events trigger callback function Twice in every single event, or “last call will be repeated” in a very short time period. The problem is that further function within callback will be triggered twice.


####################################

import dash
import dash_core_components as dcc
import dash_html_components as html
import datetime

app = dash.Dash()

app.layout = html.Div([
    dcc.Interval(id='my-interval', interval=1000*5, n_intervals=0),
    html.Div(id='display-time'),
])


@app.callback(
    output=dash.dependencies.Output('display-time', 'children'),
    inputs=[dash.dependencies.Input('my-interval', 'n_intervals')],
    events=[dash.dependencies.Event('my-interval', 'interval')])
def display_time(n):
    print ('n_intervals:' + str(n) + ' at ' + str(datetime.datetime.now()))
    # further_function_which_should_be_controlled_by_dcc.Interval()
    return "Call No.: {}; Call at: {}".format(n, str(datetime.datetime.now()))


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

Workaround could be a global variable, but this ist not cool.

############
count_n = -1

@app.callback(
    output=dash.dependencies.Output('display-time', 'children'),
    inputs=[dash.dependencies.Input('my-interval', 'n_intervals')],
    events=[dash.dependencies.Event('my-interval', 'interval')])
def display_time(n):
    global count_n
    if count_n!=n:
        print ('n_intervals:' + str(n) + ' at ' + str(datetime.datetime.now()))
        # further_function_which_should_be_controlled_by_dcc.Interval()
        count_n = n
    return "Call No.: {}; Call at: {}".format(n, str(datetime.datetime.now()))

Events and inputs both trigger callbacks. Because you have both an input and an event associated to your interval the callback is getting triggered twice each interval. Just change your callback to something like this:

@app.callback(
    output=dash.dependencies.Output('display-time', 'children'),
    inputs=[dash.dependencies.Input('my-interval', 'n_intervals')])

thanks a lot for your hint, it works as expected after removing “events=…”.
Happy new year :slight_smile:

1 Like