Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Last active January 24, 2022 05:18
Show Gist options
  • Star 22 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save peterherrmann/2700284 to your computer and use it in GitHub Desktop.
Save peterherrmann/2700284 to your computer and use it in GitHub Desktop.
GASRetry - Exponential backoff JavaScript implementation for Google Apps Script (Library project key: "MGJu3PS2ZYnANtJ9kyn2vnlLDhaBgl_dE")
* Invokes a function, performing up to 5 retries with exponential backoff.
* Retries with delays of approximately 1, 2, 4, 8 then 16 seconds for a total of
* about 32 seconds before it gives up and rethrows the last error.
* See:
<pre>//Calls an anonymous function that concatenates a greeting with the current Apps user's email
var example1 ={return "Hello, " + Session.getActiveUser().getEmail();});
</pre><pre>//Calls an existing function
var example2 =;
</pre><pre>//Calls an anonymous function that calls an existing function with an argument
var example3 ={myFunction("something")});
</pre><pre>//Calls an anonymous function that invokes DocsList.setTrashed on myFile and logs retries with the Logger.log function.
var example4 ={myFile.setTrashed(true)}, Logger.log);
* @param {Function} func The anonymous or named function to call.
* @param {Function} optLoggerFunction Optionally, you can pass a function that will be used to log
to in the case of a retry. For example, Logger.log (no parentheses) will work.
* @return {*} The value returned by the called function.
function call(func, optLoggerFunction) {
for (var n=0; n<6; n++) {
try {
return func();
} catch(e) {
if (optLoggerFunction) {optLoggerFunction("GASRetry " + n + ": " + e)}
if (n == 5) {
throw e;
Utilities.sleep((Math.pow(2,n)*1000) + (Math.round(Math.random() * 1000)));
Copy link

I've also published it as a library called GASRetry. You can add it to your own code in the Google Apps Script IDE by accessing Resources > Manage Libraries... and pasting the GASRetry project key: MGJu3PS2ZYnANtJ9kyn2vnlLDhaBgl_dE

Copy link

meksone commented Sep 15, 2016

Hi, thanks for this little and useful code. I'm implementing this code in my script (i prefer to avoid the use of libraries due performance issues) but I have problem using the optLoggerFunction that, if used, throws an error.
The error is in italian, and I try to translate:
The "log" method was called with [object Object] as "this" value and can't be converted in Logger type

Any idea?

in the meanwhile I've modified the code so the Logger is not optional and "Logger.log" is hardcoded in the function...

Copy link

kwyn commented Oct 31, 2017

you probably need to bind the logger function as Logger.log.bind(Logger)

Copy link

mgooty commented Nov 5, 2017


Copy link

notovny commented Nov 19, 2017

I wound up wrapping Logger.log in an anonymous function, which seemed to work okay.

I also modified the function to accept an array of exceptions that should be thrown immediately --For instance, if the function being passed is a wrapper for Calendar.Events.insert, you probably don't want it to keep trying on a "GoogleJsonResponseException: The requested identifier already exists" for 32 seconds before a throw.

Copy link

jcashby commented Jan 9, 2018

Hi, I'm triyng to write this retry loop into the code below but I can't seem to get it working. Please see below. Any help would be greatly appreciated as I've beeb wrapping my head around this for days now with no luck. I've left it clean without any changes to show the original script. The error I keep getting is '(TypeError: Cannot call method "getChild" of null.' and I want to retry the function to reduce the error:

function update_(trigger) {
try {
var response,
count = 0,
last = false,
data = productSheet.getDataRange().getValues();

for (var i = 2, len = data.length; i < len && !isTimeUp_(); i++) {
  last = i === len - 1;

  if (
    isEmpty_(data[i][0]) ||
    data[i][3].match('TypeError: Cannot call method "getChild" of null.'/i) ||
  ) {

  response = fetchPrice_(data[i][0]);

  if (response && response.status === '200') {

      .getRange(i + 1, 1, 1, 11)
          new Date(),

    if (!trigger) {
      ss.toast('Processing #' + (i + 1) + '. ' + response.title);
      if (i % 15 === 0) SpreadsheetApp.flush();
    } else {
      if (
        !isEmpty_(data[i][1]) &&
        !isEmpty_(data[i][11]) &&
        sendPriceAlert_(data[i], response)
        productSheet.getRange(i + 1, 12).setValue(response.price);
  } else {
      .getRange(i + 1, 4, 1, 8)
      .setValues([[response.error, '', '', '', '', '', new Date(), '']]);

} catch (e) {

function call_(func) {
for (var n = 0; n < 6; n++) {
try {
return func();
} catch (e) {
if (n == 5) {
throw e;
Utilities.sleep(Math.pow(2, n) * 1000 + Math.round(Math.random() * 1000));

Copy link

cristimocean commented May 28, 2018

Using this library makes autocomplete to dissapear.. Any idea how to get it back ?
var ss = call(function(){return SpreadsheetApp.getActiveSpreadsheet()})
var sh = ss.// no autocomplete available here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment