Skip to content

Instantly share code, notes, and snippets.

@schickling
Created December 29, 2022 11:13
Show Gist options
  • Save schickling/2cb5b66ca56ac20a11e73c2c8e38c614 to your computer and use it in GitHub Desktop.
Save schickling/2cb5b66ca56ac20a11e73c2c8e38c614 to your computer and use it in GitHub Desktop.
import { Effect as T, pipe } from '@effect-ts/core'
/** Sleeps the specified duration depending on whether the document is hidden or not */
export const sleepBackgroundForegroud = ({
durationHiddenMs,
durationVisibleMs,
}: {
durationHiddenMs: number
durationVisibleMs: number
}) => {
const startTimeMs = Date.now()
const cleanUpFns: (() => void)[] = []
return pipe(
T.effectAsync((cb) => {
const visbilityEventHandler = () => {
if (document.hidden === false) {
const elapsedMs = Date.now() - startTimeMs
if (elapsedMs >= durationHiddenMs) {
cb(T.unit)
}
}
}
document.addEventListener('visibilitychange', visbilityEventHandler)
cleanUpFns.push(() => document.removeEventListener('visibilitychange', visbilityEventHandler))
const backgroundTimeout = setTimeout(() => {}, durationHiddenMs)
cleanUpFns.push(() => clearTimeout(backgroundTimeout))
const foregroundTimeout = setTimeout(() => {
if (document.hidden === false) {
cb(T.unit)
}
}, durationVisibleMs)
cleanUpFns.push(() => clearTimeout(foregroundTimeout))
}),
T.tap(() =>
T.succeedWith(() => {
cleanUpFns.forEach((fn) => fn())
}),
),
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment