NSTimer or why does my button not work

Hi everybody,

I have a script that needs to do a few things when it launches before any button is clicked or text entered. I would like the UI to show up with my defaults and be responsive while the “background” script updates the UI as it finishes its various tasks.

This is my code:

script AppDelegate
    property parent : class "NSObject"
    property NSTimer : class "NSTimer"
    property theWindow : missing value
    property lblLabel1 : missing value
    property counter : 1
    on applicationWillFinishLaunching_(aNotification)
        NSTimer's scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(1, me, "doSomething:", "Whatever", false)
    end applicationWillFinishLaunching_
    on applicationShouldTerminate_(sender)
        return current application's NSTerminateNow
    end applicationShouldTerminate_
    on doSomething_(sender)
        repeat until counter > 10
            log "The timer fired " & counter & " times"
            lblLabel1's setStringValue_("The timer fired " & counter & " times")
            delay 0.1
            set counter to counter + 1
            do shell script "sleep 1"
        end repeat
    end doSomething_
    on startMainScript_(sender)
        log "main script started"
    end startMainScript_
    on buttonQuit_(sender)
    end buttonQuit_
end script

My log shows that doSomething runs after my startMainScript but while doSomething is running the Quit button or any other object in the UI doesn’t accept any input. Once doSomething finishes any “cached” press no the Quit button is processed right away.

So my question of the day is: how do I keep my UI responsive while doSomething is doing its thing which may take a few seconds or even minutes?


AppleScript doesn’t support multitasking, so you have to use a kludge. You have to either break the task into lots of subtasks, using one of the performSelector: methods to chain them together, or pepper the code with calls to a handler that uses nextEventMatchingMask: to maintain event handling. The latter is most efficiently done using the fordEvent method from Myriad Helpers.

Thanks, Shane,

That’s what I was afraid to hear. I will look at fordEvents and see if I can figure out how to use it.