What happens when I “sleep” in GAS ? (execution time limit workaround)

The statement that the server handler function calls aren’t independent processes because they “are created from inside the function itself” isn’t quite true.

You’ve set up a checkBox element chk1 with a server handler doSomething. Whenever the
checkBox is checked, then, an event is dispatched to the server. (…and your script is causing those events with every chk1.setValue() call) The checkBox and surrounding UI code is running in your browser – click “show source” or use an explorer to see what’s been served to your browser by the google servers. (Warning – it’s obfuscated. But you might recognize some of your strings, and from that your client-side code.)

Here’s what we’re told in the documentation for Class ServerHandler:

When a ServerHandler is invoked, the function it refers to is called on the Apps Script server in a “fresh” script.

That’s the key to extending your operating time: each dispatched event results in invocation of doSomething() in a completely new operating context – it’s like you’ve opened the script editor in a different browser, and clicked “run” on your script. The “fresh” script has no access to var values of previous run… but it is also given it’s own set of operating restrictions, including timers.

PS: You should make sure that server-side handler is “thread safe” by using Lock, since you’re accessing shared resources that may be accessed by multiple instances of the doSomething() callback. Related to that, it’s possible to hit another limit with this script:

Screenshot - error

Just for fun, I commented out .setVisible(false) on chk1, so the checkBox would be visible. I then rapidly clicked it several dozen times. The time display ran out-of-order, and eventually the above error popped up. (minutes later) It’s an artificial situation, of course, but still an error state that’s easily avoided.

PPS: I wonder if one could use the same technique to dispatch multiple parallel server-side handlers, and thus reduce the elapsed time to complete the whole job?

Leave a Comment