title: Need help optimizing a google apps script that labels emails
body: <p>Gmail has a issue where conversation labels are not applied to new messages that arrive in the conversation thread. <a href="http://www.jamesmurty.com/2008/03/13/gmail-labelling-search-bug/comment-page-1/" rel="noreferrer">issue details here</a></p>
  
  <p>We <a href="http://www.lifehacker.com.au/2011/12/fix-gmail-label-issues-with-an-app-script/" rel="noreferrer">found</a> a Google Apps Script that fixes the labels on individual messages in the Gmail Inbox to address this issue. The script is as follows:</p>
  
  <pre><code>function relabeller() {
    var labels = GmailApp.getUserLabels();
  
  
    for (var i = 0; i &lt; labels.length; i++) {
      Logger.log("label: " + i + " " + labels[i].getName());
  
      var threads = labels[i].getThreads(0,100);
      for (var j = 1; threads.length &gt; 0; j++) {
        Logger.log( (j - 1) * 100 + threads.length);
        labels[i].addToThreads(threads);
        threads = labels[i].getThreads(j*100, 100);
      }
    }
  }
  </code></pre>
  
  <p>However this script times out on email boxes with more than 20,000 messages due to the 5 mins execution time limit on Google Apps Script.</p>
  
  <p>Can anyone please suggest a way to optimize this script so that it doesn't timeout?</p>