Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท State and Events

Event Chaining with then, success and Timers

Run Gradio steps in order with .then(), .success() and .failure(), refresh data with gr.Timer, and split long work into stages. Includes error handling and race condition tips.

One click often needs several steps: validate the input, call a model, format the result, re-enable the button. You could put all of it in one function, but Gradio lets you chain events so each step is its own function, with its own inputs, outputs, progress display and API name. Chains also let the UI update between steps, for example showing "Working..." before the slow part begins. Gradio code is read-only; stand-ins implement the sequencing logic.

then, success and failure

Every event listener returns a dependency object with chaining methods:

Python
import gradio as gr
import time

def validate(text):
    if len(text.strip()) < 3:
        raise gr.Error("Please type at least 3 characters.")
    return "Working..."

def work(text):
    time.sleep(2)                    # pretend to run a model
    return text[::-1]

def done():
    return gr.Button(interactive=True), "Finished"

with gr.Blocks() as demo:
    inp = gr.Textbox(label="Text")
    status = gr.Markdown()
    out = gr.Textbox(label="Result")
    go = gr.Button("Run")

    go.click(validate, inp, status) \
      .success(work, inp, out) \
      .then(done, None, [go, status])
Method Runs the next step when
.then(fn, ...) The previous step finished, whether it succeeded or raised an error
.success(fn, ...) The previous step finished without an error
.failure(fn, ...) The previous step raised an error

In the example the first step validates and sets a status. When the text is too short, gr.Error stops the chain at .success, so the model never runs, and the user sees the red message. When valid, the status shows "Working..." while work runs, and .then always cleans up at the end (so the status does not stay stuck). Typical uses:

  • .success for the main path, .failure for logging or an apology message.
  • .then for cleanup that must always run (re-enable a button, hide a spinner).

Chaining and the UI

Every step in a chain is a separate event, so the browser updates the page after each step. That is why "Working..." is visible. If everything were one function, the page would only change at the end (unless you use generators, see generators and streaming).

You can also disable and re-enable controls around the slow step:

Python
go.click(lambda: gr.Button(interactive=False), None, go, queue=False) \
  .then(work, inp, out) \
  .then(lambda: gr.Button(interactive=True), None, go, queue=False)

queue=False makes the tiny UI steps instant instead of waiting in line behind real work. Disabling the button prevents double submission, which is the biggest cause of duplicate model calls. In practice, concurrency_limit and trigger_mode="once" solve the same problem more simply.

Timers

gr.Timer fires on an interval and can drive refreshes:

Python
import datetime

timer = gr.Timer(5)                  # every 5 seconds
clock = gr.Textbox(label="Server time")
timer.tick(lambda: datetime.datetime.now().strftime("%H:%M:%S"), None, clock)

The Textbox updates every five seconds for each connected browser. Timer(active=False) starts paused, and a function can return gr.Timer(active=True) to start it. Use timers for polling a job status or a log file. Do not use a one-second timer for heavy queries because every open tab triggers it. Consider every= on components in some versions, but the Timer is the explicit modern way.

Splitting a long job into visible stages

Python
def step1(text): ...
def step2(a): ...
def step3(b): ...

go.click(step1, inp, s1).then(step2, s1, s2).then(step3, s2, out)

Each step's output feeds the next step's input through hidden components (use gr.State for values the user need not see, covered in session state). Benefits: progress is visible, each stage shows its own errors, and each has an API endpoint. Cost: more wiring. Use chains for 2 or 3 stages, not 12.

Choose the next step

then Always, even after errors
success Only if it worked
failure Only if it failed
Timer Run every N seconds

Chain steps so the page updates between them.

1 / 2

Stand-in 1: then, success and failure

This stand-in is our own mini chain runner. It reproduces which steps run after an error.

Python Stand-in: then / success / failure

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

For "abc" the failure step is skipped; for "x" the success step is skipped, and the then step runs both times.

Stand-in 2: a timer tick loop

Python Stand-in: a polling timer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The timer polls shared job state. Real Gradio can do the same, but per-user state should live in session state, not a module-level dictionary shared by all visitors.

Pitfalls

  • A chain that writes to the same output twice can show flicker; give each step its own output or use generators.
  • .then after a failing step still runs, which can overwrite the error message; use .success when the next step depends on the first.
  • Timers keep firing for idle tabs. Pause them with gr.Timer(active=False) when nothing is happening.
  • Errors in a chain step show a toast for that step only; later .then steps still run.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method runs only if the previous step raised an error?

    failure is for error paths; success for the happy path; then for both.
  2. 2. Why does the page show 'Working...' in a chain even though the model call takes seconds?

    The first step finishes and updates the page before the next step starts.
  3. 3. What does gr.Timer(5) provide?

    Timer.tick fires on the interval and can drive polling and refresh.
  4. 4. Why use queue=False on tiny UI-only steps?

    Instant steps like enabling a button should not wait in line for model calls.

Summary

  • .then always runs next; .success after success; .failure after errors.
  • Chains update the page between steps and give each stage its own API endpoint.
  • gr.Timer fires tick on an interval for polling and refreshes.
  • Use queue=False for tiny UI updates and trigger_mode to prevent double runs.

Next: Session State with gr.State