Reputation: 1147
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
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:
10
for i
. i
becomes 10
.
10
by i=10
.1
to i
. i
becomes 11
.10
for i
. i
becomes 10
.1
to i
. i
becomes 11
.10
for i
. i
becomes 10
.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
}
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:
- 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.
- 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.
- 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