Search code examples
google-apps-scriptsequential

Google Apps Script - How to execute functions one after another?


1) My Goal

  • I'm trying to write a Google Apps Script that runs 3 functions step by step with a small pause after each step
  • Basically: 1) Fill cells with specific content 2) Send content from cells to email address 3) delete content from cells

2) My Challenge

  • Google Apps Script is running all functions simultanioulsy

3) What have I tried?

  • SpreadsheetApp.flush(); as suggested here - but did not work out

4) My Code

function pastecontent() {

  // Fetch spreadsheet 
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  
  // copy paste from first row to all others
  var source = sheet.getRange("D6:F6");
  source.copyTo (sheet.getRange("D7:F22"));  
   
}

function sendEmails() {

   // pause for X seconds  
  Utilities.sleep(3000);
 
  // Fetch spreadsheet 
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
       
  // get the range and values in one step
  var values = sheet.getRange("D7:F22").getValues();
  
  // Send Mail
  var message = values + " https://docs.google.com/spreadsheets/d/[....]"; 
  var emailAddress = "XYZ@gmail.com"; 
  var subject = "Test Mail";
  if (cell != "") {
  MailApp.sendEmail(emailAddress, subject, message);
  }
}

function clearcontent() {

  // pause for X seconds  
  Utilities.sleep(8000);

  // Fetch spreadsheet 
  var sheet = SpreadsheetApp.getActiveSpreadsheet();
  
  // clear cells
  sheet.getRange("D7:F22").clearContent();
   
}

Thanks for your support Joe


Solution

  • Main function to call all functions:

    function main() {
      pastecontent();
      sendEmails();
      clearcontent();
    }
    

    Sample Log:

    sample output

    I haven't changed anything in your code aside from the email and it went smoothly.

    Just make sure to have a main function that calls them one by one.

    Aside from that, I'm not seeing any issues with your code

    Nitpick: The cell variable wasn't defined before sending the email. Declaration wasn't included in the code provided so I declared it in mine. You might want to add that if you don't have it in yours.