Prevent Google Scripts from Exceeding the Maximum Execution Time Limit

Google Apps scripts can run for a maximum period of 4-5 minutes and you’ll get the error “Exceeded maximum execution time” if the script takes more than the allowed time to complete.

The Save Gmail Attachments and Extract Gmail Addresses scripts fetch 50 Gmail threads in a single batch and processes the messages one by one. If any particular thread is long, the overall execution time may exceed the limit and the script may throw an exception.

To prevent the error from happening, inside the loop, we can keep a track of time since the script is running and elegantly stop when it is nearing the time limit.