Skip to content

Instantly share code, notes, and snippets.

@tomhodgins
Created June 23, 2021 15:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomhodgins/b9f947e863a78181d4e23ff30305f679 to your computer and use it in GitHub Desktop.
Save tomhodgins/b9f947e863a78181d4e23ff30305f679 to your computer and use it in GitHub Desktop.
class InactivityCountdown {
constructor(
callback = () => {},
duration = 10
) {
this.timer // to hold setTimeout ID
this.active = false // remember timer state
this.callback = callback // function to run when countdown completes
this.duration = duration // time in seconds to wait
}
start() {
// If timer is not active, start it
if (this.active === false) {
this.active = true
this.timer = setTimeout(
this.callback,
this.duration * 1000
)
// If timer is already active, reset it
} else {
this.reset()
}
}
stop() {
// If timer is active, stop it
if (this.active === true) {
this.active = false
clearTimeout(this.timer)
}
}
// Reset timer by stopping and restarting it
reset() {
this.stop()
this.start()
}
}
// Demo: create lack of activity countdown for modal
const modalTrigger = new InactivityCountdown(
() => {
const tag = document.querySelector('cre-book-modal')
// If modal found, open it
if (tag !== null) {
tag.dispatchEvent(new CustomEvent('open'))
}
},
5 // seconds
)
// Start timer right away…
modalTrigger.start()
// …and listen for events to reset the timer
;[
'click', // mouse
'keydown', // keyboard
'touchstart', // touchscreen
'scroll'
].forEach(eventType =>
window.addEventListener(eventType, event => modalTrigger.reset())
)
// Tests
function runTests() {
const test1 = new InactivityCountdown
console.log('New Countdown is')
console.log(test1)
const test2 = new InactivityCountdown(() => {console.log('test 2 succeeded')})
console.log('Countdown with timer')
test2.start()
const test3 = new InactivityCountdown(() => {console.log('test 3 succeeded')}, 5)
console.log('Countdown with timer and duration')
test3.start()
}
// runTests()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment