idle

MGS [2003/04/04] - I wanted a way to cache idle commands i.e. to be able to schedule the same command multiple times (before the event loop is re-entered), and then have the command run only once. Following Darren New's code snippet, I came up with this simple solution:

 proc idle {args} {
     eval after cancel $args
     return [eval after idle $args]
 }

AK: In 8.5 or later

 proc idle {args} {
     after cancel {*}$args
     return [after idle {*}$args]
 }

MGS [2011/09/19] - Ok, nearly 8 1/2 years later, I've just realised this doesn't do what I had originally intended. It only cancels the execution of a single delayed command, NOT all delayed commands with the same args. We need to do a little more work:

 proc idle {args} {
     set scr [eval [linsert $args 0 concat]]
     foreach id [after info] {
         set info [after info $id]
         if { [string equal $scr [lindex $info 0]] &&
              [string equal idle [lindex $info 1]] } {
            after cancel $id
         }
     }
     return [after idle $scr]
 }

See also: