title: API calls respecting rate-limits using counter with delays, how to? javascript google apps script
body: <p>I have about 50k lines of data that need to be queried over an API service. The service limites it's API calls as follows:</p>
  <ul>
  <li>per second: max 50</li>
  <li>per minute: max 2.500</li>
  <li>per hour:   max 25.000</li>
  <li>per day:    max 50.000</li>
  <li>per month:  max 100.000</li>
  </ul>
  <p>I am focusing on the limits per second and minute for now, looping through all rows and stopping if the rate limit went over:</p>
  <pre><code>var app = SpreadsheetApp;
  var sheet = app.getActiveSpreadsheet().getSheetByName(&quot;data&quot;);
  var maxRows = sheet.getLastRow();
  var maxColumns = sheet.getLastColumn();
  var data = sheet.getrange(2,1,maxRows,maxColumns).getValues();
  
  var rateLimitSec = 50;
  var rateLimitMin = 2500;
  var rateLimitSecUsed = 0;
  var rateLimitMinUsed = 0;
  
  function example () {
      for ( 
      i=0; 
      (i&lt;=maxRows) || (rateLimitSecUsed&lt;rateLimitSec) || (rateLimitMinUsed&lt;=RateLimitMin);
      i++
    )
      { // start loop code
              // do the API request
        rateLimitSecUsed = rateLimitSecUsed+1 // and increase Rate limit used marker
        rateLimitMinUsed = rateLimitMinUsed+1
        
        if ( !(rateLimitMinUsed &lt; RateLimitMin) ) {
          // stop for now, or add better solution later. show some warning;
        } else if ( !( rateLimitSecUsed !&lt; rateLimitSec) ) {
  
  --&gt;&gt;    Utilities.sleep(1000); // HERE I WANT A DELAY FOR 1S, &lt;&lt;---
  
          rateLimitSec = 0; // reset limit after delay.
          example(); // call function again after delay
        }
        
      } // end loop code
  }; // end function example
  </code></pre>
  <p>This is not working as intended though. I read somewhere that this would not work because of asynchronicity, and that I would need to use the <a href="https://developers.google.com/apps-script/reference/lock/lock" rel="nofollow noreferrer">class lock</a>. However, I can't figure out how the lock class works. Can anyone help guide me in the right direction on this? Is the lock class the right solution and, if yes, how does it work?</p>
  <p>Also, is my approach for keeping the rate limits in check good or are there better ways of doing this?</p>
  <p>This should be a pretty common issue, but I can't find any decent examples on this.</p>
  <p>EDIT: found some typo's in the example code, fixes what i found. Don't worry too much about all that, the focus of the question is &quot;how do i add a delay between one loop and the next, to make sure I don't go over the API-limit?&quot;</p>