Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
How to change the scope of a variable to global in google sheets script editor?

I am trying to create a stopwatch google sheets implementation that uses cells rather than buttons. However, I can't figure out how to make my [sec] variable global so that changes are shown when it is put into the cell. I do NOT want to use buttons as a trigger.

Code

function onEdit(e) {
  
  var range = e.range;
  var spreadSheet = e.source;
  var sheetName = spreadSheet.getActiveSheet().getName();
  var column = range.getColumn();
  var row = range.getRow();
  var inputValue = e.value;
  //Clock variables
  var hr = 0;
  var min = 0;
  var sec = 0;
  var stopTime = true; 
  //need to make seconds a global variable

  if(sheetName == 'timer' && column == 1 && row == 2 && inputValue == "start"){  
    SpreadsheetApp.getActiveSpreadsheet().getSheetByName('timer').getRange('B2').setValue("00:00:00");  
    stopTime = false;
    while (stopTime == false ) {
      sec = sec + 1;
        if (sec == 60) {
          min = min + 1;
          sec = 0;
        }
        if (min == 60) {
          hr = hr + 1;
          min = 0;
          sec = 0;
        }

        if (sec < 10 || sec == 0) {
          sec = '0' + sec;
        }
        if (min < 10 || min == 0) {
          min = '0' + min;
        }
        if (hr < 10 || hr == 0) {
          hr = '0' + hr;
        }
      }
  } 
if(sheetName == 'timer' && column == 1 && row == 2 && inputValue == "stop"){
  SpreadsheetApp.getActiveSpreadsheet().getSheetByName('timer').getRange('C2').setValue([sec]);  
}
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!