SetTimer()

Auto Hotkey

SetTimer

Causes a subroutine to be launched automatically and repeatedly at a specified time interval.

SetTimer Label, Period|On|Off, Priority
Command  Example: SetTimer "MyTimer", 100
Function Example: SetTimer("MyTimer", 100)

Parameters

Label

The name of the label or hotkey label to which to jump, which causes the commands beneath Label to be executed until a Return or Exit is encountered. As with the parameters of almost all other commands, Label can be a variable reference such as %MyLabel%, in which case the name stored in the variable is used as the target.

If Label is omitted, A_ThisLabel will be used. For example, SetTimer,, Off can be used inside a timer subroutine to turn off the timer, while SetTimer,, 1000 would either update the current timer's Period or set a new timer using the label which is currently running. If A_ThisLabel is empty but the current thread was launched by a timer, that timer is used. This is useful for timers which launch functions or function objects.

If not a valid label name, this parameter can be the name of a function, or a single variable reference containing a function object. For example, SetTimer %funcobj%, 1000 or SetTimer % funcobj, 1000. Other expressions which return objects are currently unsupported. See the class example for more details.

Note: Passing an empty variable or an expression which results in an empty value is considered an error. This parameter must be either given a non-empty value or completely omitted.

Period|On|Off|Delete

On: Re-enables a previously disabled timer at its former period. If the timer doesn't exist, it is created (with a default period of 250). The timer is also reset. If the timer exists but was previously set to run-only-once mode, it will again run only once.

Off: Disables an existing timer.

Delete: Disables and deletes an existing timer. If the timer is associated with a function object, the object is released. Turning off a timer does not release the object.

Period: Creates or updates a timer using the absolute value of this parameter as the approximate number of milliseconds that must pass before the timer is executed. The timer will be automatically enabled and reset. It can be set to repeat automatically or run only once:

  • If Period is positive, the timer will automatically repeat until it is explicitly disabled by the script.
  • If Period is negative, the timer will run only once. For example, specifying -100 would run the timer 100 ms from now then disable the timer as though SetTimer, Label, Off had been used.

    If Label is an object created by the script (not an actual function or label), the timer is automatically deleted after the timer function returns, unless the timer was re-enabled. This allows the object to be freed if the script is no longer referencing it, but it also means the timer's Period and Priority are not retained.

Period must be an integer, unless a variable or expression is used, in which case any fractional part is ignored. Its absolute value must be no larger than 4294967295 ms (49.7 days).

Default: If this parameter is blank and:
1) the timer does not exist: it will be created with a period of 250.
2) the timer already exists: it will be enabled and reset at its former period unless a Priority is specified.

Priority

This optional parameter is an integer between -2147483648 and 2147483647 (or an expression) to indicate this timer's thread priority. If omitted, 0 will be used. See Threads for details.

To change the priority of an existing timer without affecting it in any other way, leave the parameter before this one blank.

Remarks

Timers are useful because they run asynchronously, meaning that they will run at the specified frequency (interval) even when the script is waiting for a window, displaying a dialog, or busy with another task. Examples of their many uses include taking some action when the user becomes idle (as reflected by A_TimeIdle) or closing unwanted windows the moment they appear.

Although timers may give the illusion that the script is performing more than one task simultaneously, this is not the case. Instead, timed subroutines are treated just like other threads: they can interrupt or be interrupted by another thread, such as a hotkey subroutine. See Threads for details.

Whenever a timer is created, re-enabled, or updated with a new period, its subroutine will not run right away; its time period must expire first. If you wish the timer's first execution to be immediate, use Gosub to execute the timer's subroutine (however, this will not start a new thread like the timer itself does; so settings such as SendMode will not start off at their defaults).

Reset: If SetTimer is used on an existing timer and parameter #2 is a number or the word ON (or it is omitted), the timer is reset; in other words, the entirety of its period must elapse before its subroutine will run again.

Timer precision: Due to the granularity of the OS's time-keeping system, Period is typically rounded up to the nearest multiple of 10 or 15.6 milliseconds (depending on the type of hardware and drivers installed). For example, a Period between 1 and 10 (inclusive) is usually equivalent to 10 or 15.6 on Windows 2000/XP. A shorter delay may be achieved via Loop+Sleep as demonstrated at DllCall+timeBeginPeriod+Sleep.

Reliability: A timer might not be able to run as often as specified under the following conditions:

  1. Other applications are putting a heavy load on the CPU.
  2. The timer subroutine itself takes longer than its own period to run, or there are too many other competing timers.
  3. The timer has been interrupted by another thread, namely another timed subroutine, hotkey subroutine, or custom menu item (this can be avoided via Critical). If this happens and the interrupting thread takes a long time to finish, the interrupted timer will be effectively disabled for the duration. However, any other timers will continue to run by interrupting the thread that interrupted the first timer.
  4. The script is uninterruptible as a result of Critical or Thread Interrupt/Priority. During such times, timers will not run. Later, when the script becomes interruptible again, any overdue timer will run once as soon as possible and then resume its normal schedule.

Although timers will operate when the script is suspended, they will not run if the current thread has "Thread NoTimers" in effect or whenever any thread is paused. In addition, they do not operate when the user is navigating through one of the script's menus (such as the tray icon menu or a menu bar).

Because timers operate by temporarily interrupting the script's current activity, their subroutines should be kept short (so that they finish quickly) whenever a long interruption would be undesirable.

Other remarks: Timers that stay in effect for the duration of a script should usually be created in the auto-execute section. By contrast, a temporary timer might often be disabled by its own subroutine (see examples at the bottom of this page).

Whenever a timed subroutine is run, it starts off fresh with the default values for settings such as SendMode. These defaults can be changed in the auto-execute section.

If hotkey response time is crucial (such as in games) and the script contains any timers whose subroutines take longer than about 5 ms to execute, use the following command to avoid any chance of a 15 ms delay. Such a delay would otherwise happen if a hotkey is pressed at the exact moment a timer thread is in its period of uninterruptibility:

Thread, interrupt, 0  ; Make all threads always-interruptible.

If a timer is disabled while its subroutine is currently running, that subroutine will continue until it completes.

The KeyHistory feature shows how many timers exist and how many are currently enabled.

Related

Gosub, Return, Threads, Thread (command), Critical, IsLabel, Menu

Examples

; Example #1: Close unwanted windows whenever they appear:
SetTimer, CloseMailWarnings, 250
return

CloseMailWarnings:
WinClose, Microsoft Outlook, A timeout occured while communicating
WinClose, Microsoft Outlook, A connection to the server could not be established
return

 

; Example #2: Wait for a certain window to appear and then alert the user:
SetTimer, Alert1, 500
return

Alert1:
if !WinExist("Video Conversion", "Process Complete")
    return
; Otherwise:
SetTimer,, Off  ; i.e. the timer turns itself off here.
MsgBox, The video conversion is finished.
return

 

; Example #3: Detection of single, double, and triple-presses of a hotkey. This
; allows a hotkey to perform a different operation depending on how many times
; you press it:
#c::
if winc_presses > 0 ; SetTimer already started, so we log the keypress instead.
{
    winc_presses += 1
    return
}
; Otherwise, this is the first press of a new series. Set count to 1 and start
; the timer:
winc_presses := 1
SetTimer, KeyWinC, -400 ; Wait for more presses within a 400 millisecond window.
return

KeyWinC:
if winc_presses = 1 ; The key was pressed once.
{
    Run, m:\  ; Open a folder.
}
else if winc_presses = 2 ; The key was pressed twice.
{
    Run, m:\multimedia  ; Open a different folder.
}
else if winc_presses > 2
{
    MsgBox, Three or more clicks detected.
}
; Regardless of which action above was triggered, reset the count to
; prepare for the next series of presses:
winc_presses := 0
return

 

; Example #4: Using a method as the timer subroutine.

counter := new SecondCounter
counter.Start()
Sleep 5000
counter.Stop()
Sleep 2000

; An example class for counting the seconds...
class SecondCounter {
    __New() {
        this.interval := 1000
        this.count := 0
        ; Tick() has an implicit parameter "this" which is a reference to
        ; the object, so we need to create a function which encapsulates
        ; "this" and the method to call:
        this.timer := ObjBindMethod(this, "Tick")
    }
    Start() {
        ; Known limitation: SetTimer requires a plain variable reference.
        timer := this.timer
        SetTimer % timer, % this.interval
        ToolTip % "Counter started"
    }
    Stop() {
        ; To turn off the timer, we must pass the same object as before:
        timer := this.timer
        SetTimer % timer, Off
        ToolTip % "Counter stopped at " this.count
    }
    ; In this example, the timer calls this method:
    Tick() {
        ToolTip % ++this.count
    }
}

Tips relating to the above example:

  • We can also use this.timer := this.Tick.Bind(this). When this.timer is called, it will effectively invoke this.Tick.Call(this) (except that this.Tick is not re-evaluated). By contrast, ObjBindMethod produces an object which invokes this.Tick().
  • If we rename Tick to Call, we can just use this directly instead of this.timer. This also removes the need for the temporary variable. However, ObjBindMethod is useful when the object has multiple methods which should be called by different event sources, such as hotkeys, menu items, GUI controls, etc.
  • If the timer is being modified or deleted from within a function/method called by the timer, it may be easier to omit the Label parameter. In some cases this avoids the need to retain the original object which was passed to SetTimer, which eliminates one temporary variable (like timer in the example above).