The Google Apps spreadsheet script occasionally fails to complete iteration but functions properly in all other aspects

I have a script that goes through a spreadsheet of student data one row at a time to email students and their parents if the student's grade is below 60. The spreadsheet columns include: Student ID, Name, Email Address, Parent's Email Address, and Grade. There are 30 rows in the sheet but only up to 25 will be used. Some parent email addresses may be blank, which is handled in the code. All students have email addresses.

The script works fine, except it stops running before completing all iterations. It randomly stops after a different number of runs each time without any error messages. Any thoughts on why this might be happening?

Here is the code I am using:

function onOpen(){
  loadMenu();
}

function loadMenu() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.addMenu("F-Watch Emailer", [{"name":"Send Emails", "functionName":"sendEmails"}]);
}

function sendEmails() {
  var ss  = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var range = sheet.getRange("B2:E30");
  var data = range.getValues();

  for (var i = 0; i < 30; i++){
    var row = data[i];
    var emailAddress = row[1];
    var parentEmailAddress = row[2];
    var grade = row[3];

    if(emailAddress !== ""){
      sendStudentEmail(emailAddress, grade);     
    }

    if(parentEmailAddress !== ""){
      sendParentEmail(parentEmailAddress, grade);     
    }
  }
}

function sendStudentEmail(emailAddress, grade){
  if(grade < 60){
    var subject = "Weekly F-Watch Email for Mr. Lipson's Class";
    var body = "Attention Students: If your grade is below 60, please check iPass and speak with me. Have a good day, - Mr. L";
    //MailApp.sendEmail(emailAddress, subject, body);
    return true;
  }
  else{
    return false;
  }
}

function sendParentEmail(parentEmailAddress, grade){
  if(grade < 60){
    var subject = "Weekly F-Watch Email for Mr. Lipson's Class";
    var body = "Parent Email Text";
    //MailApp.sendEmail(emailAddress, subject, body);
    return true;
  }
  else{
    return false;
  }
}

Answer №1

When troubleshooting a for loop that isn't working properly, consider using the debugger to step through the code.

To set a breakpoint at a specific line in your script, simply double-click near the line number in the editor. You can then run the debugger by clicking on the spider icon.

Answer №2

It's common to encounter uncharted boundaries, and in those instances utilizing Utilities.Sleep(ms) can be a helpful solution

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the technique for determining the XPath location of an element through Javascript

Imagine you have a lengthy HTML file filled with various tags, much like the layout of Stack Overflow. If you were to click on a specific element on the page, what would the Javascript function look like to determine the simplest XPath that points to that ...

Issue with Moment.js: inability to append hours and minutes to a designated time

I have a starting time and I need to add an ending time to it. For example: start=19:09 end=00:51 // 0 hours and 51 minutes I want to add the 51 minutes to the 19:09 to make it 20:00. I've attempted several different methods as shown below, but none ...

Could you clarify that for me?

Let's take a look at the function isIsogram(str) which checks if a string is an isogram. An isogram is a word or phrase in which no letter occurs more than once. The code snippet for this function can be seen below: We are particularly interested in ...

Obtain the value of the background image's URL

Is there a way to extract the value of the background-image URL that is set directly in the element tag using inline styling? <a style="background-image: url(https:// ....)"></a> I attempted to retrieve this information using var url = $(thi ...

Pairing strings with arrays

I'm trying to compare elements in two arrays and see if there are any matches. However, I can't seem to get it working correctly. let name; let list = ["Kat", "Jane", "Jack"]; // sample array let input = ["Hey", "i'm", "Jack"]; if (input.fo ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Using `getJson` to parse the tree structure

I am currently working with a JSON file that contains order data. The structure of the JSON file is as follows: { "orders": [ {"name": "Peter", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="64140110011624050b0 ...

Encountering a `Syntax Error` in a Jade view

I am attempting to create a basic chat application using the simple jade view engine with express. Upon running my app, I encountered a syntax error in the following view code, even though it seems quite straightforward. extends layout block scrip ...

Trigger a function following a collection update in Angular Meteor

I am in the process of developing a multiplayer game, and I would like a specific function to be triggered once the first player updates an "isStarted" field in the collection. Within my controller code: angular.module('mcitygame').directive(&a ...

Add a dynamic widget to a specific element in the document object model in real time

Is there a way to dynamically create a jQuery UI widget using a string? You can easily do this by following the example below: $(function() { $("selector").widget() }) However, what I am trying to accomplish is slightly different. Here is an examp ...

What is the best way to display a child element in the right panel?

Hello, I need help in displaying child elements next to the parent element. My function works fine the first time, but fails the second time. Here are the steps I followed: 1) Clicked the Add button 2 times, generating row2 as well as a submenu of firs ...

Implement jQuery to dynamically assign an "Active" class to tab elements based on the current page being loaded

INQUIRIES I have include: How do I apply a class to an element using jQuery, or any other method, for the active tab? Ensure that the dropdown tab appearing is the one containing the active tab, not always the Company one. In essence, I want the ac ...

Avoid clicking on links while the webpage is still loading

I am facing an issue with my website where I need to intercept link-clicking events using jQuery. Everything works fine, but there is a problem if a user clicks on a link before JavaScript finishes loading, causing it to redirect to another page in error. ...

Assign the value in the text box to the PHP session variable

Currently, I am developing a PHP "interactive text game" as a part of my assignment project. My task involves creating a user interface where users input information (such as character names) into text boxes that appear sequentially as they complete the p ...

Help with guiding and redirecting links

Here's the code snippet: <script> if(document.location.href.indexOf('https://thedomain.com/collections/all?sort_by=best-selling') > -1) { document.location.href = 'https://thedomain.com/pages/bestsellers'; } </script& ...

Tips on successfully transferring row data that has been clicked or selected from one adjacent table to another table

Currently, I am facing a challenge with two tables that are positioned next to each other. My goal is to append a selected row from the first table to the second table. After successfully extracting data from the selected row and converting it into an arr ...

What is the best way to conceal an element solely in live production environments?

Is there a way in my Angular code to specifically target the PROD environment? <div *ngIf="environment !== 'prod'" class="col-6"> <button class="btn btn-primary text-white add-photo" (cli ...

Embedding Array into Mongodb is an efficient way to store and

Whenever I attempt to store array data within MongoDB using the query below, it always shows a success message without actually storing any data in an empty array inside MongoDB. My goal is to successfully store array data inside MongoDB as shown in the f ...

What is the best way to store JSON data in a MySQL database?

I am facing a challenge with a JavaScript rich page that is sending a large JSON formatted data to PHP for insertion into a MySQL database. The JSON contains user input strings, some of which may include basic HTML tags like <a> and <strong>. ...

Encountering cross-domain issues while integrating AngularJS in flex (web control), and trying to retrieve templates/json (local files)

To provide some background on my current endeavor, I am utilizing a Flex application to serve as a container for a web app. Within this Flex app resides a web controller that loads a complete Angularjs application. All necessary files are stored locally wi ...