I’m trying to find out two things.
- Can I optimize my code so that it will run faster
- Is there a way to test the speed of my script.
My script is simply pulling data from a URL (Example: https://www.sciencebase.gov/catalog/items?q=Water&max=100&format=json) that will be pasted into the first cell of a spreadsheet. It then populates the cells with the first column storing the title and the second column storing the summary.
I’m using a trigger that will execute the script onEdit() so that it will run whenever a edit is made to the first cell of the spreadsheet.
Any pointers, tips, or even a go look here is appreciated
Here’s my code,
function respondToSearch() {
// Gets the active sheet in a spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Gets sheet 1 and sets the first column to a width of 200 and the second
column to width 500
var sheet = ss.getSheets()[0].setColumnWidth(1, 200).setColumnWidth(2, 500);
var activeSheet = SpreadsheetApp.getActiveSheet();
// Gets the value from the top left cell in a range
var dataRange = activeSheet.getDataRange().getValue();
// Sends an HTTP request to fetch the URL
var searchResponse = UrlFetchApp.fetch(dataRange);
// Get the response as a string and parse (string is in JSON format)
var parsedResponse = Utilities.jsonParse(searchResponse.getContentText());
// Array to hold letter corresponding to spreadsheet columns
var cellLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l",
"m", "n", "o", "p", "q", "r", "s", "t"];
// Loop through the "item" objects and display the properties in the
spreadsheet
for (var i = 0; i < 2; i++) {
for (var j = 0; j < parsedResponse.items.length; j++) {
// Starts with items[0] (1st object) and displays the properties
var parsedItems = [parsedResponse.items[j].title, parsedResponse.items[j]
.summary];
// If a property is not undefined print the property in the spreadsheet
else print "N/A"
if (parsedItems[i] != undefined) {
var print = parsedItems[i];
}
else {
var print = "N/A";
}
// Stores the current letter corresponding to the current spreadsheet column
var cellLtr = cellLetters[i];
// Starts the row available to display data at number 2
var cellNum = [j + 2];
var cell = cellLtr + cellNum;
sheet.setActiveCell(cell).setFontSize("9").setHorizontalAlignment("left")
.setVerticalAlignment("top").setValue(print);
}
}
}
Thank you
I think it is possible. Try to rewrite your code to set the font size and the alignments not for every cells but for the whole range.
Yes. The code should looks line the following