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.

/* Based on */

function isTimeUp_(start) {
  var now = new Date();
  return now.getTime() - start.getTime() > 300000; // 5 minutes

function myFunction() {
  var threads = GmailApp.getInboxThreads(0, 50);  
  var start = new Date();
  for (var t in threads) {
    if (isTimeUp_(start)) {
      Logger.log("Time up");
    // Process the thread otherwise    
    var messages = threads[t].getMessages();