Google Apps Script – Ways to protect buttons from being pressed?

For example: In my Google Spreadsheets document there is a timer with a start and stop button. So far everything works. But if someone clicks on the ‘stop’ button by mistake although the timer is currently not running, it will causes issues and let the timer display a large and incorrect time. So I’m searching for methods to gray out the ‘stop’ button until ‘start’ was pressed. After, ‘start’ should be grayed out and ‘stop’ now available.

Has anybody ideas?

And then there’s that I’m a total beginner in terms of scripting so the best bet would be if someone could help me out with the the script code 🙂

Thanks in advance!

Best regards, Marco

Answer

Best method to prevent a script to run in parallel is to use the Lock Service. When your button is pressed, you run a method that will acquire a lock and release it when finished. If you happen to click the button while previous task is still running, the lock acquire will fail and you can for example show an alert or just ignore the error.

function onButtonClick(){
  const lock = LockService.getDocumentLock()  
  try{
    lock.waitLock(1000)
    // do some work
  } catch(e){
    if(e.message.indexOf('Lock')>=0){
      SpreadsheetApp.getUi().alert(e.message)
    }    
  } finally{
    lock.releaseLock()
  }
}