Tcl event loop and timers
last modified November 24, 2026 Tcl 8.6
A console script normally runs from the first line to the last and then exits. Many programs cannot work that way: a network client has to wait for bytes, a GUI has to react to clicks, an installer has to update a progress line every so often. Tcl solves this with an event loop. The script registers callbacks, the loop waits for something to happen, and then runs the matching callback.
The loop is the same one that drives Tk, but it also works without any window.
This article explains what the loop is, how timers are scheduled with
after, how to cancel and inspect them, how update and
vwait give the loop a chance to run, and how to watch a channel
without blocking. The after command page has the
reference details; here the commands are used in small complete programs.
What the event loop is
An event is a small record of something that happened: a timer expired, a
channel became readable, a file descriptor changed. Tcl keeps events in a queue.
Commands such as after or fileevent do not run anything
themselves; they register a script together with the condition that should
trigger it. Only when the interpreter is inside the event loop does it take an
event from the queue and evaluate the associated script.
A plain tclsh script is not inside the loop. It is busy executing
commands, and when the last command returns the interpreter exits, taking the
queue with it. The next script schedules a timer and then ends, which is enough
to show that scheduling alone does nothing.
proc remind {} {
puts "timer: fired"
}
puts "main: scheduling a timer"
after 100 remind
puts "main: script ends here"
The after line schedules the procedure for 100 milliseconds in the
future and returns immediately. The last line prints, and then the script is
over. The message from the timer never appears, because no part of the program
ever entered the event loop. In a Tk program the loop is started by
mainloop; in a console script it is entered by vwait
or update.
$ tclsh loop_needed.tcl main: scheduling a timer main: script ends here
Scheduling a script with after
The two-argument form after ms script puts the script into the
queue and returns an identifier. The delay is in milliseconds. When the delay
has passed and the loop is running, the script is evaluated at global level,
exactly as if it had been typed at the prompt. The single-argument form
after ms is different: it sleeps and stops everything, including
the loop, and is not used here.
proc report {what} {
puts "reminder: $what"
}
puts "main: scheduling"
after 200 [list report "tea is ready"]
after 400 [list report "call Jane"]
after 700 {set finished 1}
vwait finished
puts "main: loop finished"
Each call to after receives a script built with list,
so the procedure name and its argument stay separate words when the callback is
evaluated. The callbacks run in the order of their delays, not in the order in
which they were registered. The last one writes the variable
finished, and vwait is waiting for
exactly that; when the variable changes, the loop returns and the final line
runs. Delays are minimums: a callback that runs late pushes the ones behind it.
$ tclsh after_script.tcl main: scheduling reminder: tea is ready reminder: call Jane main: loop finished
Cancelling timers: after cancel and after info
The identifier returned by after is a timer token such as
after#0. It can be stored and used later with
after cancel, which removes the pending event; the command also
accepts the script text instead of the token. The after info
command lists the pending tokens, and with a token as its argument it returns a
two-element list holding the script and the kind of event, which is either
timer or idle.
set first [after 300 {puts "first timer"}]
set second [after 600 {puts "second timer"}]
puts "script behind $first: [lindex [after info $first] 0]"
proc drop {id} {
after cancel $id
puts "cancelled $id"
}
after 100 [list drop $first]
after 800 {set finished 1}
vwait finished
The first two lines register two timers and keep their tokens. The third line
asks after info about the first one and prints the script that is
waiting there. A third timer, due after 100 milliseconds, calls
drop, which cancels the 300 millisecond timer before it has a
chance to fire; the output confirms that the cancellation happened and that only
the second timer printed. Cancelling a timer that has already run is harmless,
which makes cleanup code simpler.
$ tclsh cancel_info.tcl script behind after#0: puts "first timer" cancelled after#0 second timer
Running code when the loop is idle
Not every callback is urgent. Some work, such as redrawing a status line or
recomputing a summary, should happen when nothing else is waiting. The
after idle script form registers such a callback. Idle handlers run
only when the queue holds no event that is ready, so a busy program can postpone
them for a while, but they always run before the loop blocks waiting for new
events.
after 50 {puts "timer at 50 ms"}
after idle {puts "idle handler"}
after idle {puts "second idle handler"}
after 100 {set finished 1}
puts "main: scheduled"
vwait finished
Both idle handlers run before the 50 millisecond timer, because at the moment
the loop starts there is no ready timer and the idle queue is served first. They
run in the order in which they were registered. The 50 millisecond timer then
fires, and after 100 milliseconds the variable finished is written,
which ends the wait. In a GUI the same mechanism is used for work that should
not delay the redraw of a widget.
$ tclsh idle_demo.tcl main: scheduled idle handler second idle handler timer at 50 ms
Processing pending events with update
A long computation that never returns to the loop freezes timers, channels and
windows. The update command gives the loop one pass: it processes
every event that is ready right now, including idle handlers, and then returns
to the caller. Calling it inside a loop keeps an interface alive while the
script is busy, at the price of allowing callbacks to run in the middle of the
computation.
after idle {puts "idle handler"}
after 0 {puts "zero-delay timer"}
after 200 {puts "timer at 200 ms"}
puts "before update"
update
puts "after update"
after 300 {set finished 1}
vwait finished
Inside update, the zero-delay timer is already due, so it runs
first; the idle handler follows because the queue has no other ready event. The
200 millisecond timer is not due yet, so update returns and the
script continues. That timer prints later, while vwait keeps the
loop running until the 300 millisecond callback sets finished. This
ordering is the practical difference between update and
vwait: the first makes one pass, the second keeps going.
$ tclsh update_demo.tcl before update zero-delay timer idle handler after update timer at 200 ms
Waiting for a variable with vwait
A console program usually needs a reason to stay alive, and vwait
supplies one: it runs the event loop until the named variable is written. Any
callback, any channel handler, any traced assignment can satisfy the wait. The
variable does not have to change value; writing the same value is enough. This
is why the examples use a flag called finished or done
instead of an endless wait, which would have to be stopped with Ctrl+C.
set state "waiting"
after 100 {set state "first write"}
after 300 {
puts "the 300 ms timer also ran"
set state "second write"
}
vwait state
puts "vwait returned: $state"
vwait state
puts "vwait returned again: $state"
The first vwait returns as soon as the 100 millisecond callback
writes the variable, so the script prints the first value and stops waiting.
The second vwait then waits for the next write, which comes from
the 300 millisecond callback; that callback also prints its own line first.
Timers keep running between the two waits because the queue was never
discarded. Nested waits are allowed but tricky: a callback that writes the
variable of an outer wait can end that wait earlier than expected.
$ tclsh vwait_demo.tcl vwait returned: first write the 300 ms timer also ran vwait returned again: second write
Repeating timers
Tcl has no interval timer that repeats by itself. The idiomatic way to repeat is to have the callback register itself again, usually with the same delay. The next tick is measured from the end of the current callback, so the period is the delay plus the work done, and the drift adds up in a long run. For a clock that must stay on the second, compute the delay from the current time instead.
set ticks 0
proc tick {} {
global ticks
incr ticks
puts "tick $ticks"
if {$ticks < 4} {
after 100 tick
} else {
set ::done 1
}
}
after 100 tick
vwait done
puts "stopped after $ticks ticks"
The procedure increments a global counter, prints it, and schedules the next
call while the counter is below four. On the fourth call it sets
done in the global namespace, which releases the
vwait. The counter is a global because the callback runs at global
level and a local variable would not survive between calls. Replacing
after 100 tick with after 100 [list tick $someValue]
passes state forward without globals.
$ tclsh repeat_timer.tcl tick 1 tick 2 tick 3 tick 4 stopped after 4 ticks
Non-blocking channels with fconfigure and fileevent
Reading from a pipe or a socket normally blocks until data arrives, which would
stop the loop and every other callback. fconfigure can switch a
channel to non-blocking mode, and fileevent then registers a script
that the loop runs whenever the channel becomes readable. Inside the callback,
gets returns -1 both when no complete line is available
and at end of file, so the handler checks eof to tell
the two cases apart.
set ch [open {|sh -c "for i in 1 2 3; do echo line $i; sleep 0.1; done"} r]
fconfigure $ch -blocking 0 -buffering line
proc on_readable {ch} {
if {[gets $ch line] >= 0} {
puts "got: $line"
} elseif {[eof $ch]} {
fileevent $ch readable {}
close $ch
set ::finished 1
}
}
fileevent $ch readable [list on_readable $ch]
vwait finished
puts "channel closed"
The channel comes from a shell loop that prints a line every tenth of a second,
so the data really arrives in pieces; the processes
article explains the pipe form in more detail. Non-blocking mode makes
gets return immediately. Each readable event produces one line,
and at the end the handler removes itself with an empty script, closes the
channel and sets the flag, so the loop has no reason to call it again.
$ tclsh fileevent_demo.tcl got: line 1 got: line 2 got: line 3 channel closed
A progress and status example
The pieces combine into the kind of program that shows progress during a long job. Each step is one callback; when it finishes it prints its status and schedules the next step, so the loop stays free between steps. A real application would do the work inside the callback instead of just printing its name, but the structure is the same.
set steps {download unpack verify install}
set total [llength $steps]
set index 0
proc advance {} {
global steps total index
set name [lindex $steps $index]
incr index
set percent [expr {$index * 100 / $total}]
puts "[format %3d%% $percent] $name"
if {$index < $total} {
after 120 advance
} else {
set ::done 1
}
}
puts "starting $total steps"
after 120 advance
vwait done
puts "all $total steps finished"
The procedure reads the current step from a list, advances the index and
computes an integer percentage. format %3d%% pads the number to
three columns and prints a literal percent sign, so the lines stay aligned as
the number grows from 25 to 100. The callback reschedules itself until the list
is exhausted, then sets done and lets vwait return.
Because the work is broken into short callbacks, a window or a socket could be
served between any two steps.
$ tclsh progress_demo.tcl starting 4 steps 25% download 50% unpack 75% verify 100% install all 4 steps finished
Source
The Tcl 8.6 manual documents the event loop from the script side. The pages for
after, vwait, fconfigure and
fileevent cover the options used above, and the Tk manual explains
mainloop, which is the same loop running until the last window
closes.
This article explained the event loop as a queue of callbacks: timers scheduled
with after, cancelled with after cancel and inspected
with after info, idle handlers, one-pass update,
vwait as a stop condition, self-rescheduling timers, and
non-blocking channels driven by fileevent. The vwait command page goes further into nested waits, and
the binary data article shows how to read the
bytes such a callback receives.
Author
List all Tcl Tutorials.