Created
December 29, 2022 11:13
-
-
Save schickling/2cb5b66ca56ac20a11e73c2c8e38c614 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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