Skip to content

Instantly share code, notes, and snippets.

@saikyun
Created April 2, 2025 07:49
Show Gist options
  • Save saikyun/e823c360aaa29e1f019400557ade0367 to your computer and use it in GitHub Desktop.
Save saikyun/e823c360aaa29e1f019400557ade0367 to your computer and use it in GitHub Desktop.
node script that runs a timer while the lid is open, pauses on lid close. Macos only.
const exec = require("node:util").promisify(require("node:child_process").exec)
const get = (l, n) => (l == null ? null : l.length <= n ? null : l[n])
const lid_open = async () => {
const { stdout: res } = await exec(
"ioreg -r -k AppleClamshellState -d 4 | grep AppleClamshellState | head -1"
)
const re = /.*"AppleClamshellState" = (No|Yes).*/
return get(re.exec(res), 1) == "No"
}
var timer = 1000 * 60 * 25
var open = true
const main = async () => {
var start = Date.now()
console.log("Started:", new Date(start).toLocaleTimeString())
const f = async () => {
const was_open = open
open = await lid_open()
if (was_open && !open) {
console.log("Paused:", new Date(start).toLocaleTimeString())
}
if (!was_open && open) {
console.log("Resumed:", new Date(start).toLocaleTimeString())
}
console.log(
open,
`${("0" + Math.floor(timer / 60000)).slice(-2)}:${(
"0" + Math.floor((timer % 60000) / 1000)
).slice(-2)}`
)
const cur = Date.now()
if (!was_open && open) {
start = cur
} else {
const delta = cur - start
start = cur
if (open) timer -= delta
}
if (timer <= 0) {
exec("say done")
}
setTimeout(f, 1000)
}
f()
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment