Edge
Edge

Reputation: 2540

AHK - Sleep inside a function doesn't work

The following code works as expected:

time := 1000

<^q::
    Sleep time
    SendInput {F9}
return

However, the following code does not (it ignores Sleep entirely), and I'm unsure as to why:

time := 1000

<^q:: 
    doKeys()
return

doKeys()
{
    Sleep time
    SendInput {F9}
}

Upvotes: 3

Views: 1164

Answers (2)

errorseven
errorseven

Reputation: 2672

Your first example works because the Variable Time is accessible to the code contained within your Subroutine (gosub).

Functions

A function is similar to a subroutine (Gosub) except that it can accept parameters (inputs) from its caller. In addition, a function may optionally return a value to its caller.

time := 1000

<^q:: 
    doKeys(time) ; Pass your variable to the function
return

doKeys(x) ; Set your function to accept a variable
{
    Sleep x
    SendInput {F9}
}

Alternatively you could declare a variable as Global so that it is accessible without passing it to the function.

time := 1000

<^q:: 
    doKeys() 
return

doKeys() 
{
    global time
    Sleep time
    SendInput {F9}
}

Upvotes: 4

Schneyer
Schneyer

Reputation: 1257

Make the variable global:

time := 1000

<^q:: 
    doKeys()
return

doKeys()
{
    global time
    Sleep time
    SendInput {F9}
}

Note: If you use #Warn, AHK will give you a warning if there are common errors like this in the code.

Upvotes: 2

Related Questions