Oday Salim
Oday Salim

Reputation: 1147

Simple For Loop Google Apps Script

I am attempting to write a very basic For loop in Google Apps Script, which really should run quickly. However, when I execute it, it takes a long time to run until I get an error that it took too long to run (Error: Exceeded maximum execution time).

Code is:

function myFunction() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var Sheet = ss.getActiveSheet();
  var LR = Sheet.getLastRow()

  for(var i=1;i=10;i++)

  {
   Logger.log(i);
  }

}

Am I doing something wrong? Or is my Google Apps Script is screwed up?

Upvotes: 0

Views: 3546

Answers (1)

Tanaike
Tanaike

Reputation: 201683

Your loop is never finished.

In your script, i=10 of for(var i=1; i=10; i++) has to be condition. But i=10 is that it substitutes 10 for i. Therefore, when for(var i=1; i=10; i++) is run:

  1. At 1st loop, it substitutes 10 for i. i becomes 10.
    • 1 of the initial value is replaced to 10 by i=10.
  2. At 2nd loop, it adds 1 to i. i becomes 11.
  3. At 3rd loop, it substitutes 10 for i. i becomes 10.
  4. At 4th loop, it adds 1 to i. i becomes 11.
  5. At 5th loop, it substitutes 10 for i. i becomes 10.

Solution:

When you want to loop from 1 to 10, how about modifying to like this?

for (var i = 1; i <= 10; i++) {
  // do something
}

Also, for example, when you want to loop 10 times, how about modifying to like this?

for (var i = 0; i < 10; i++) {
  // do something
}

About issue:

The documentation of the Javascript for statement describes:

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. A for statement looks as follows:

for ([initialExpression]; [condition]; [incrementExpression])
  statement

When a for loop executes, the following occurs:

  1. The initializing expression initialExpression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. This expression can also declare variables.
  2. The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates. If the condition expression is omitted entirely, the condition is assumed to be true.
  3. The statement executes. To execute multiple statements, use a block statement ({ ... }) to group those statements. If present, the update expression incrementExpression is executed. Control returns to step 2.

Upvotes: 5

Related Questions