Alim
Alim

Reputation: 23

Why does my Google App script auto refresh code not work?

I wrote a simple code to automatically refresh the digits in the Google sheet. I print the i with app script to the relevant place. Data needs to be refreshed every 15 seconds. But it doesn't work right. It should write 0 at the 15th second, 1 at the 30th, 2 at the 45th. But 0 doesn't write 1, it just writes the 2 in the last loop. Why doesn't it write data every 15 seconds?

function exampleFunction() {
  var app = SpreadsheetApp;
  var spreadSheet = app.getActiveSpreadsheet();
  var activeSheet = spreadSheet.getSheetByName("sheetname");
  var i = 0;

  while(true){
    activeSheet.getRange(1, 1).setValue(i);
    i++;
    Utilities.sleep(15000);
    
    if(i == 3){
      break;
    }
  }

Upvotes: 0

Views: 737

Answers (1)

Marios
Marios

Reputation: 27348

For documentation reasons, I can confirm Tanaike's comment, it works with SpreadsheetApp.flush() as it is expected:

function exampleFunction() {
  var app = SpreadsheetApp;
  var spreadSheet = app.getActiveSpreadsheet();
  var activeSheet = spreadSheet.getSheetByName("sheetname");
  var i = 0;

  while(true){
    activeSheet.getRange(1, 1).setValue(i);
    SpreadsheetApp.flush()
    i++;
    Utilities.sleep(15000);
    
    if(i == 3){
      break;
    }
  }
}

Upvotes: 1

Related Questions