简体   繁体   中英

How can I toggle SetTimer off with a hotkey in AutoHotKey?

I am trying to write a script toggling a function.

This is an AutoHotkey 2 Script.

j::
    SetTimer "NewTimer", 1000
    return

k::
    SetTimer "NewTimer", Off
    return

NewTimer() {
    SendInput "NewInput"
}

Pressing J should start the timer, pressing K should stop it. Currently, pressing K only stops it as long as I hold the key down. How can I stop the timer with the key press?

k::
SetTimer "NewTimer" , "Off"
Return

Off must be in quotes, otherwise it will try to pass the contents of the varaible "Off". The reason holding K seems to pause it is because it's rapidly updating the period to the value contained in Off which is null and an error, so it reverts to the previous period of 1000.

Alternatively, if this is the only timer, using just SetTimer , "Off" also works.

You can consider that excerpt from the official docs for SetTimer :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM