0

I wanted to toggle between two functions on every run in Google Apps Script. This codes didn't work. I was replied that Google Apps Script declares global variable each time.

var toggle = true;

function toggleFunction() {
  toggle ? functionA() : functionB();
  toggle = !toggle;
}

function functionA() {
  console.log('toggle is true')
}

function functionB() {
  console.log('toggle is false')
}

As advised, I adopted CasheService for global variable with which the following codes are working now as I want. I realize toggle variable was being saved as string in CasheService. So I needed to convert it to boolean with toggle = (toggle === 'true'). Is this a correct way?

function toggleFunction() {
  var toggle = CacheService.getScriptCache().get('toggle');
  toggle = (toggle === 'true');
  toggle ? functionA() : functionB();
  toggle = !toggle;
  CacheService.getScriptCache().put('toggle', toggle);
}

function functionA() {
  console.log('toggle is true')
}

function functionB() {
  console.log('toggle is false')
}
Newbie
  • 247
  • 3
  • 11

0 Answers0