Search code examples
google-apps-scriptgoogle-sheetscustom-function

Is there a way to call a custom function every couple of seconds in Google Apps Script?


I'm trying to make a silly but simple little program in google apps script and sheets where it picks a random dad joke to show you every couple of seconds. I tried using setInterval(), but I found out that it isn't included in google apps script. Any suggestions?

code:

function LOL() {
  let messageList = ["Where do dads keep their jokes? In a dad-abase!","When does a joke become a dad joke? When it becomes a-parent!","Two men walk into a bar. You'd think the second one would've noticed!","Does your face hurt? 'Cause it's killing me!"]
  function randInt() {
    let listLength = messageList.length
    let random = Math.floor(Math.random() * listLength);
    return random
  }
  function showMessage() {
    let int = randInt()
    console.log(int)
    return messageList[int]
  }
  return showMessage()
}

It would choose a random message from my list every minute to put in whatever cell has =LOL().


Solution

  • Here I found a solution by Tanaike that will update a custom function by using a TextFinder and combined it with Time driven trigger to automatically refresh it every minute.

    Try this:

    Code:

    function LOL(){
      let messageList = ["Where do dads keep their jokes? In a dad-abase!","When does a joke become a dad joke? When it becomes a-parent!","Two men walk into a bar. You'd think the second one would've noticed!","Does your face hurt? 'Cause it's killing me!"]
      let listLength = messageList.length
      let random = Math.floor(Math.random() * listLength);
      return messageList[random];
    }
    
    function refresher() {
      const sheet = SpreadsheetApp.getActiveSheet();
      const formula = "=LOL";
      sheet.createTextFinder("^\\" + formula).matchFormulaText(true).useRegularExpression(true).replaceAllWith("Loading");
      sheet.createTextFinder("Loading").matchFormulaText(true).useRegularExpression(true).replaceAllWith(formula);
    }
    

    Installable Trigger Setup:

    enter image description here

    Output:

    enter image description here

    enter image description here