Gopinath Shiva
Gopinath Shiva

Reputation: 3892

Google Script for adding timer

I am trying to create a google script which consist of 2 button "start" and "stop". Clicking "Start" will start a timer and clicking "stop" will stop a timer.

I do know I cant achieve this using setTimeout or setInterval, so I used utilities.sleep(1000) . But using this I cant execute the function more than 5 minutes because of limitation set by Google.

Hence I tried using Trigger methods setting at 1 second, but no luck. The triggering is not happening at all.

I am sharing the code below any help is appreciated.

function onClickStart(){
  startTimer();
}

function startTimer() {
  removeJobs();
  ScriptApp.newTrigger("timer")
  .timeBased()
  .after(1000)
  .create();

  timer();
}

function removeJobs() {    

  PropertiesService.getScriptProperties().deleteAllProperties();
  var triggers = ScriptApp.getProjectTriggers();
  for (i=0; i<triggers.length; i++) {
    ScriptApp.deleteTrigger(triggers[i]);
  }
}

function timer() {
  var seconds = 0, minutes = 0, hours = 0,
    t,stop_time;

  var documentProperties = PropertiesService.getDocumentProperties();
  var timer = documentProperties.getProperty('timer_result');
  Logger.log('get timer: %s', timer);
  if(timer){
    timer = timer.split(':');
    seconds = +timer[2] || 0 ;
    minutes = +timer[1] || 0 ;
    hours = +timer[0] || 0 ;
  }
    seconds++;
    if (seconds >= 60) {
        seconds = 0;
        minutes++;
        if (minutes >= 60) {
            minutes = 0;
            hours++;
        }
    }

    stop_time = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
    SpreadsheetApp.getActiveSheet().getRange('F7').setValue(stop_time); 
    Logger.log('set timer: %s', stop_time);
    documentProperties.setProperty('timer_result', stop_time);
}

Upvotes: 1

Views: 16721

Answers (1)

Spencer Easton
Spencer Easton

Reputation: 5782

Every time you call timer() from a trigger a unique instance of your script is created and when the execution chain is done it is destroyed. All global variables are removed when the instance is destroyed. So right now every time the trigger is called seconds, minutes, hours are set to 0.

For persistent data between instances use the property service. https://developers.google.com/apps-script/reference/properties/

Upvotes: 1

Related Questions