Best Practices for Multiple OnEdit Functions

Notes:

  • There can only be one function with a same name. If there are two, the latter will overwrite the former. It’s like the former never existed.
  • A function named onEdit is triggered automatically on (You guessed it!)edit
  • There’s no simple trigger for other names like onEdit1 or onEdit2….
  • Simple triggers are limited to 30 seconds of execution
  • So, in a single code.gs file or even in a single project, there can only be one function named onEdit and trigger successfully.
  • If you create multiple projects, onEdit will trigger in each project asynchronously. But there are limits to number of projects that can be created and other quotas will apply.
  • Alternatively, you can use installed triggers: which doesn’t have limit of 30s. You can also use any name for your function.
  • The best way to optimize functions is to never touch the spreadsheet unless it is absolutely necessary. For example, sorting various values inside the script is better than repeatedly calling .sort on the multiple ranges multiple times. The lesser the interaction between sheets and scripts, the better. A highly optimized script will only require two calls to spreadsheet: one to get the data and the other to set the data.
  • After optimizing the number of calls to sheet, you can optimize the script itself: Control the logic such that only the necessary amount of operations are done for each edit. For example, if the edit is in A1(A1,B1 are checkboxes, if clicked clears A2:A10,B2:B10 respectively), then you should check if A1 is clicked and If clicked, clear the range and exit and not to check for B1 again. Script optimization requires atleast a basic knowledge of JavaScript objects. Nevertheless, this isn’t as effective as reducing the number of calls-which is the slowest part of any apps script.

References:

Leave a Comment