Skip to content

Instantly share code, notes, and snippets.

@justinsbarrett
Created September 12, 2020 00:04
Show Gist options
  • Save justinsbarrett/c60be9bbc5a73e22245648666127e8d1 to your computer and use it in GitHub Desktop.
Save justinsbarrett/c60be9bbc5a73e22245648666127e8d1 to your computer and use it in GitHub Desktop.
/**
* Title: Record Timer (Automation)
* Version: 1.0
* License: MIT
* Author: Justin S Barrett
* Sites:
* http://www.justinsbarrett.com - Main website
* https://www.youtube.com/channel/UCElPqW_1xVXToQPB3Y_WD3Q - All About That Base
*
* Description: An alternative to Airtable's built-in timer block. With this script,
* you can start and stop virtual timers directly on individual records. Any record's
* timer may be started and stopped multiple times, allowing for easy tracking of
* staggered timing sessions. This version is designed to be triggered by Airtable's
* automation system.
*
* Requirements: Before using this script, you will need to add the following fields:
* - A single select field to start/stop the timer. This should only contain one
* option. The text of that option is irrelevant, but I like "Running" which
* serves as a visual reminder of that record's timer state
* - A single line text field to store the timer data (may be hidden)
* - A duration field to store the total tracked time
*
* Automation Setup: The automation must use the "When a record is updated" trigger,
* which will look for changes to the single select field mentioned above.
*
* Input Variables: The following input variables must be added to the script action:
* timerData Data from the single line text field that stores timer data
* triggerValue The "Name" property of the single select field driving the timer
* recordID The record ID of the triggering record
*
* Version History:
* 09/11/2020 1.0 Initial release
*
*/
// Get the record
let config = input.config();
let timerData = config.timerData;
let values = timerData === null ? [] : JSON.parse(timerData);
let duration;
// Get the current time and store its value in the array
let currentTime = new Date();
values.push(currentTime.getTime());
// Check the trigger field value to see if we're starting or stopping
if (config.triggerValue) {
// Not-empty = starting. Clear the duration field
duration = null;
} else {
// Empty = stopping. Find the difference between the value pairs
duration = 0;
let index = 0;
while (values.length % 2 == 0 && index<values.length) {
duration += values[index + 1] - values[index];
index += 2;
}
// Divide by 1000 to get seconds
duration /= 1000;
}
// Save output values
output.set("duration", duration);
output.set("timerData", JSON.stringify(values));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment