Home > Software engineering >  Google apps script for docs: fire every second or mimic onEdit
Google apps script for docs: fire every second or mimic onEdit

Time:12-21

I'm looking to allow a google docs user to turn the background of a given text range yellow by typing an exclamation point. This sounds like onEdit, which I know exists in sheets but not in docs. I saw this workaround on GitHub, but it requires adding a sidebar and inserting HTML, which I'd rather not do.

This answer discusses an onEdit workaround, but it still has the trigger fire every 60 seconds, rather than, say, every second.

This answer lays out how to call a function every second, and I'm trying to get it to work, but I can't figure it out. Here's what I have:

function myFunction() {
  for (var i = 0; i < 10; i  ) {
    var doc = DocumentApp.openByUrl('Doc URL');
    var body = doc.getBody();
    var text = body.editAsText();
    Logger.log(body.findText('!'))
    if (body.findText('!') != null) {
      text.setBackgroundColor(13, 50, '#FFFF00');
      Utilities.sleep(1000);
    }
    ScriptApp.newTrigger("myFunction")
      .timeBased()
      .after(1000)
      .create();
  }
}

The function runs once, then sends me the error message, "Exception: This script has too many triggers. Triggers must be deleted from the script before more can be added." I don't have any triggers added other than what's in this function. I suspect the answer might be a while loop instead, but I'm a beginner and I'm not sure. What should I do?

CodePudding user response:

The function you show will create ten triggers that run that very function after a second. When those ten copies run, they each create another ten triggers. So after one second you would have 10 triggers, after two seconds you would have 100 triggers, after three seconds you would have 1000 triggers, and so on. In practice, you get an error like the one you mention almost right away.

What you need is exactly one trigger. Use getProjectTriggers() to find whether a trigger already exists, and only create a trigger if there are none. You should also move the trigger creation code outside the loop.

  • Related