The GAS platform does not provide such as persistent runtime memory equipment during the lifetime of an app: from the UI initialization (, and user interactions, and) to the termination of application. (closing the browser)
It seems on the surface the global variable declaration looks valid over all local scopes (functions) as the standard JS defines, but in effect, it will not be for eventhandlers because each invocation will reload the entire code on a brand-new copy of runtime memory (this is probably why it is so slow..), and all the states of the previous run will be inaccessible, as the following sample code will display ‘2’ on the textbox for button clicks all the time:
I wish GAS team elaborates this and at least document it for saving any further brain burns.
One way-around I found for making any states (values or objects, stringified) persistent over events is that saving it somewhere on the active UI. It will make your code strange but it will be cheaper than backup/restore the values using a spreadsheet for each invokes.
As Johninio pointed out in the original post, the proposed method can be elaborated as the following:
tag:script | tag:programming | tag:demo