Skip to content
Advertisement

Google Script – Opting out of a loop before it’s finished, returns later to finish the loop

I have a bit of a weird problem. I built a script that will essentially take variable information from Spreadsheet 1, it will then create a copy of EmptySheet, fill out all the information row by row (let’s refer to it as FilledInSheet after).

After that it takes FilledInSheet and deletes the requested tabs. This all works perfectly, except that the last row to be filled in, that row is skipped, the copyfile for 4 is created, and AFTER that the FilledInSheet is updated with the right information.

I have spent hours and hours trying to fix this, any feedback is much appreciated. Again, everything works except the code seems to skip one row loop, and then comes back to it later?

I have tried to boil the code down as much as possible, but please let me know if anyone has additional questions.

JavaScript

Advertisement

Answer

Use SpreadsheetApp.flush()

  • This will ensure that the script execution will pause and wait for the request within one loop to be completed before the next loop iteration starts.

  • Without this the script runs asynchronously and a request execution could start before the previous one(s) is completely finished.

  • SpreadsheetApp.flush() only works for calls to the SpreadsheetApp, so a good position to place it is after calling a SpreadsheetApp method that you expect to be slow.

Sample:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement