UserInput Google Scripts非常慢

时间:2016-04-01 11:51:18

标签: javascript google-apps-script google-sheets

我做了一个食物记录器。我正在尝试创建一个脚本,允许我在Sheet [1]中添加一行,并添加一个新的食物源,如果它还没有在那里。此代码在此处有效,但执行起来非常慢。每个问题之间大约有一秒钟。是否有可能使执行更快,或者可能在一个提示中要求所有4个值?

 // Display a dialog box with a title, message, input field, and "Yes" and "No" buttons. The
 // user can also close the dialog by clicking the close button in its title bar.
function foodSource(){ 
var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Tilføjelse af madvare', 'Hvilken madvare er det?', ui.ButtonSet.OK);
  return response.getResponseText();
}
function protein(){ 
var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Mængde pr 100 gram', 'Protein', ui.ButtonSet.OK);
  return response.getResponseText();
}
function carbonhydrates(){ 
var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Mængde pr 100 gram', 'Kulhydrater', ui.ButtonSet.OK);
  return response.getResponseText();
}
function fat(){ 
var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Mængde pr 100 gram', 'Fedt', ui.ButtonSet.OK);
  return response.getResponseText();
}



function addData(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[1];

 sheet.appendRow([madvare(),100, protein(), carbonhydrates(), fat()]); 
}

1 个答案:

答案 0 :(得分:0)

每次API调用都需要“大量时间”,因此为了加快脚本速度,我们应该减少API调用。

在公开的代码中,有三个函数,每个函数都调用SpreadsheetApp.getUI。执行时间可以减少,只使用一个,因为它没有改变。

执行上述操作的一种方法是将这三个功能集成到第四个功能中(未经测试):

 // Display a dialog box with a title, message, input field, and "Yes" and "No" buttons. The
 // user can also close the dialog by clicking the close button in its title bar.

function addData(){

  /*
   *  Get ui only once
   */
  var ui = SpreadsheetApp.getUi();

  //Get foodsource
  var response = ui.prompt('Tilføjelse af madvare', 'Hvilken madvare er det?', ui.ButtonSet.OK);
  var foodsource = response.getResponseText();

  //Get protein
  var response = ui.prompt('Mængde pr 100 gram', 'Protein', ui.ButtonSet.OK);
  var protein = response.getResponseText();

  // Get carbohydrates
  var response = ui.prompt('Mængde pr 100 gram', 'Kulhydrater', ui.ButtonSet.OK);
  var carbonhydrates = response.getResponseText();

  //Get fat
  var response = ui.prompt('Mængde pr 100 gram', 'Fedt', ui.ButtonSet.OK);
  var fat = response.getResponseText();

  //Append a row with the collected data
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[1];
  sheet.appendRow([foodsource,100, protein, carbonhydrates, fat]); 
}