Skip to content

Instantly share code, notes, and snippets.

@edulan
Last active October 2, 2017 16:03
Show Gist options
  • Save edulan/158a5bd35a9210a35139e8b2b51cb5b4 to your computer and use it in GitHub Desktop.
Save edulan/158a5bd35a9210a35139e8b2b51cb5b4 to your computer and use it in GitHub Desktop.
Idle timer
function createIdleTimer (delay = 5E3) {
const IDLE_POLL_TIMEOUT = 1E2
const events = ['mousemove', 'mousedown', 'keydown', 'touchstart', 'scroll']
return new Promise((resolve) => {
let idle = true
let timeout = null
let lastTimestamp = null
let elapsedTimeInMillis = 0
function registerEvents () {
events.forEach((event) => window.addEventListener(event, handleEvent))
}
function unregisterEvents () {
events.forEach((event) => window.removeEventListener(event, handleEvent))
}
function signalTimer () {
unregisterEvents()
resolve()
}
function handleEvent () {
if (elapsedTimeInMillis > delay) {
signalTimer()
return
}
if (idle) {
idle = false
lastTimestamp = Date.now()
}
clearTimeout(timeout)
timeout = setTimeout(() => {
idle = true
elapsedTimeInMillis += Date.now() - lastTimestamp
if (elapsedTimeInMillis > delay) {
signalTimer()
}
}, IDLE_POLL_TIMEOUT)
}
registerEvents()
})
}
createIdleTimer().then(() => console.log('5 seconds of activity!'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment