Home > Back-end >  Is there a way to call a custom function every couple of seconds in Google Apps Script?
Is there a way to call a custom function every couple of seconds in Google Apps Script?

Time:10-28

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().

CodePudding user response:

Here I found a solution by enter image description here

Output:

enter image description here

enter image description here

CodePudding user response:

You can use the native Utilities.sleep from Serge's Answer, although I would recommend using a Trigger or async functions if you need to do anything else in the script.

Here's a quick example of implementation:

function myFunction() {
  var delayInMilliseconds = 5000; //1 second
  while (true){
    Utilities.sleep(delayInMilliseconds)
    showMessage()
  }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can manage Time-driven triggers manually, e.g. run a particular function everyHour(). See here

  • Related