My AutoHotkeyScript Jams up after clicking the hotkey too many times

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
JMH5909
Posts: 2
Joined: 23 Jan 2022, 13:03

My AutoHotkeyScript Jams up after clicking the hotkey too many times

Post by JMH5909 » 23 Jan 2022, 13:10

What it is supposed to do is when you click Ctrl+K it will toggle wiggling your cursor every 50 seconds (basically anti-afk) and it will constantly display a message saying its on when it is, and it will give a short message saying when its turned off. This is all fine and dandy but if you click it too many times (maybe before the seconds have passed or something) it seems to freeze. Try it out for yourself, here is my code.

Code: Select all

#NoEnv ; Recommended for performance and compatibility with future AutoHotkey releases.
; #Warn  ; Enable warnings to assist with detecting common errors.
SendMode Input ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir% ; Ensures a consistent starting directory.
#MaxThreadsPerHotkey 2 ; Two Threads
wait := 50

^k:: 
    toggle := !toggle
    Loop 
    { 
        if (not toggle) {
            tooltip "Toggle Off"
            SetTimer, RemoveToolTip, 500
            break
        }

        SetTimer, RemoveToolTip, Off
        ToolTip "Toggle On"

        Sleep, % wait*1000
        Mousemove, 10, 0, 20, R
        Sleep, 100
        Mousemove, -10, 0, 20, R

    }
    ; tooltip "Toggle Off"
    ; SetTimer, RemoveToolTip, 500

return

RemoveToolTip:
    ToolTip

Return

User avatar
mikeyww
Posts: 26951
Joined: 09 Sep 2014, 18:38

Re: My AutoHotkeyScript Jams up after clicking the hotkey too many times

Post by mikeyww » 23 Jan 2022, 13:13

Every time you trigger it, a new thread is launched and interrupts the previous one. Upon completion, the previous thread resumes. If you trigger it more than the max threads before the routines finish, you may get unexpected results.

Your timer loop will repeat infinitely until the timer is disabled.

JMH5909
Posts: 2
Joined: 23 Jan 2022, 13:03

Re: My AutoHotkeyScript Jams up after clicking the hotkey too many times

Post by JMH5909 » 23 Jan 2022, 13:14

What should I do to fix this

User avatar
mikeyww
Posts: 26951
Joined: 09 Sep 2014, 18:38

Re: My AutoHotkeyScript Jams up after clicking the hotkey too many times

Post by mikeyww » 23 Jan 2022, 13:19

I'd say that you have five main options.

1. Trigger less often.
2. Increase max threads.
3. Add a new hotkey variant that does something different if the routine is already running.
4. Block the keyboard until the routine finishes (not my favorite option).
5. Use a timer instead of a loop (often a good choice). The hotkey can toggle the timer.

Code: Select all

F3::SetTimer, Go, % (f3 := !f3) ? 100 : "Off"
Go:
MouseMove, 100, 100
Send x
Return

Post Reply

Return to “Ask for Help (v1)”