Skip to content

Instantly share code, notes, and snippets.

@phillypb
Last active November 11, 2024 11:46
Show Gist options
  • Save phillypb/e1b533d483499bf862f7ce55a3395afd to your computer and use it in GitHub Desktop.
Save phillypb/e1b533d483499bf862f7ce55a3395afd to your computer and use it in GitHub Desktop.
/**
* Code to learn about Exponential Backoff.
* Developed when experiencing 'Rate Limit' issue with updating a Calendar Event of Attendees.
*
* DEVELOPED BY THE GIFT OF SCRIPT: https://www.pbainbridge.co.uk/
*/
function mainFunction() {
console.log("Starting the process");
try {
// how many times the 'while' loop should iterate through
var count = 3;
// the delay in how long the code should wait before retrying, in milliseconds
var backOff = 2000; // 2 seconds
// call Function
var returnMessage = testBackOff(count, backOff);
// only displayed if previous Function completed successfully without error/throw
console.log("returnMessage is: " + returnMessage);
} catch (error) {
console.log("Catch error is: " + error.stack);
};
};
function testBackOff(count, backOff) {
// loop through for the number of times specified in Parent Function
while (count > 0) {
try {
console.log("count is: " + count);
// create a defined error message with 50% chance (0.5) of triggering when the code is run
if (Math.random() < 0.5) {
throw new Error("API call to calendar.events.patch failed with error: Rate Limit Exceeded");
};
return "Successfully updated Calendar Attendees.";
} catch (error) {
// convert 'catch' message to string and perform JavaScript 'match' for keywords
var errorString = error.toString();
var matching = errorString.match(/Rate Limit Exceeded/gi);
// test if 'match' is true to display specific log message
if (matching) {
// log message
console.log('Message match found');
// decrement count by 1;
count -= 1;
// if count is 0 then number of iterations has been reached
if (count == 0) {
// return error message to 'catch' of Parent Function
throw (error);
} else {
// pause code for backoff period before trying again
Utilities.sleep(backOff);
// double length of backoff period each time
backOff *= 2;
};
} else {
// log message
console.log('Different message found.');
throw (error);
};
};
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment