For Loops timing out: JavaScript / Google Apps Script

放肆的年华 提交于 2021-02-13 17:27:26

问题


So I am have this issue with Google Apps Script. It is timing out because the app server requests are taking too long. I was just wanting to see if my coding could be cleaned up a bit to run faster or is there another method which would work?

Code below:

for (var y = 1; y < listLast ; y++) {

  var matchor = listSheet.getRange("B" + y).getValue();
  var listEmCo = listSheet.getRange("A" + y).getValue();
  if(matchor == "Match") {
    Logger.log("Do Nothing");
  } else {
  for (var x = 0; x < formLast; x++) {

  if(listEmCo == formData[x]){

    listSheet.getRange("B"+ [y]).setValue("Match");
    break;

  } else {

    listSheet.getRange("B"+ [y]).setValue("No Match");

   }
  }
 }   
}

Thanks for any responses :)


回答1:


Do not use .getValue(); in a loop. This operation is heavy.

Please use range.getValues() and then loop the array to get values.

The plan is:

  1. get the initial range
  2. get data with var data = range.getValues();
  3. make empty array to write new values array = [];
  4. Loop the data and make new array, fill it with proper values [["value1"], ["value2"], ...,]. Note. It should be a 2D-Array.
  5. After the loop define a range to paste new values: rangeTo
  6. Use rangeTo.setValues(array); to paste new values.

See more:

  • https://developers.google.com/apps-script/guides/support/best-practices
  • https://sheetswithmaxmakhrov.wordpress.com/2017/11/02/scripts-working-with-arrays-in-sheets/

Tag #Another-get-data-from-range-question

See more questions on topic:

http://stackoverflow.com/questions/39859421/google-script-internal-error-after-15-seconds

http://stackoverflow.com/questions/39586911/google-script-exceeded-maximum-execution-time-help-optimize

http://stackoverflow.com/questions/38618266/google-sheet-script-times-out-need-a-new-way-or-flip-it-upside-down

http://stackoverflow.com/questions/44021567/google-sheet-script-multiple-getrange-looping

Code runs too slow



来源:https://stackoverflow.com/questions/47774322/for-loops-timing-out-javascript-google-apps-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!