Try setting "logged in" and "error message" as a static variable maybe? Otherwise they will reset to default value after a tick, e.g. after the wait. But I'm not sure why it works when not in a function.
You could also split the function up some more, and instead of setting local vars you call a "login success" or "login error" function (runtime.callfunction) with whatever parameters you need.