On Idle Handler Theory

This is simply a “why does AppleScript do this question”. I put only the following code in a stay-open AppleScript application:

on idle
    beep
    tell me to quit
    return 5
end idle

I assumed that upon launching the app, it would beep once and immediately quit. That’s not what happens. It beeps once, waits 5 seconds, and then quits–without beeping a second time. Since it is not beeping twice, it can’t be running through the code twice . Apparently it is not handling the quit statement until after the time specified in the return value.

Why? I’m perplexed. :confused:

Thanks

Brett

Model: Power Mac G5 Dual 2GHz
AppleScript: 1.10.3
Browser: Firefox 1.0.4
Operating System: Mac OS X (10.4)

I have only the most vague idea of how this works, but if you’ll entertain an wild guess… could the issue be that “me” refers to the run handler which doesn’t get control back until the 5 seconds are up?

What happens if you change the “tell me to quit” to just “quit”?

I’m sure someone more knowledgeble will chime in.

Common misassumption. Sending a ‘quit’ command doesn’t force an immediate exit. That would be gross bad manners. It merely instructs the applet shell to shut down the next time the script returns control to it. Use something like:

on idle
    set shouldQuit to true
    beep
    if shouldQuit then
        tell me to quit
        return 1 -- (shortest delay possible)
    end tell
    return 5
end idle

Thanks! I always like to know the reasons behind why something is behaving a certain way. Now I’ve learned something new about how AppleScript runs. :slight_smile:

Thanks again

Model: Power Mac G5 Dual 2GHz
AppleScript: 1.10.3
Browser: Firefox 1.0.4
Operating System: Mac OS X (10.4)

For me, there’s a difference between Tiger and Jaguar in this respect. In Jaguar, the script always idles for the set time before quitting, as described above. In Tiger (10.4.2, AS 1.10), the ‘quit’ works instantaneously if it occurs in the idle handler’s first call as part of the script’s initial run, but the effect is delayed if ‘quit’ is invoked on a subsequent call.

property shouldFinish : true

on idle
	beep
	if shouldFinish then
		quit
	end if
	
	return 5
end idle
--> Jaguar: Beeps once and quits five seconds later.
--> Tiger: Beeps once and quits immediately.


property shouldFinish : false

on idle
	beep
	if shouldFinish then
		quit
	end if

	set shouldFinish to true
	return 5
end idle
--> Both systems: Beeps once, twice, then waits another five seconds before quitting.