user2416983
user2416983

Reputation: 23

How to set a timer in Google Apps Script?

I have written a small program in Google Apps Script to borrow and hand in items through a "UI" in Google Sheets. The user finds an item in a dropdown list, enter their name, and click a button to borrow. Similarly, when handing in a device, the user finds the item to hand in in another dropdown and click another button.

What I would like is to show some kind of feedback to the user when the item has been registered as borrowed or handed in. The problem is not to show a message, but to make it disappear again. Therefore, I would like some kind of timer that removes the notification after a few seconds.

I searched for a solution and found that I might be able to use 'Utilities.sleep', but it seems to just wait the specified amount of time and then execute the entire code at once no matter how I structure it.

I was thinking something as simple as this:

var range = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('B2');

range.setValue('The item was successfully registered!');
Utilities.sleep(3000);
range.clear();

I also looked into the 'Lock.waitlock' but couldn't get that to work either. I did see this post, but for some reason it doesn't work for me: Set Timeout in Google Apps Scripts

Any help would be appreciated.

Upvotes: 0

Views: 4272

Answers (1)

oshliaer
oshliaer

Reputation: 4969

For the fully imitation of your code

  var range = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange('B2');
  range.setValue('The item was successfully registered!');
  SpreadsheetApp.flush();
  Utilities.sleep(3000);
  range.clear();

But for me, I think It's a bad idea.

You can use a long display toast:

  var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  activeSpreadsheet.toast('The item was successfully registered!', 'Automation', -1);
  Utilities.sleep(3000);
  activeSpreadsheet.toast('All fine! Relax!', 'Automation', 5 * 1000);

Upvotes: 1

Related Questions