Reputation: 2412
In my Vue app, I have a place where I'm setting a timer. I'd like to interrupt the timer if the user presses any key or clicks anywhere in the browser window.
I do not want to stop whatever they clicked from happening. I just want to get a callback whenever it does.
I could just put a function call in every handler, but that is both tedious, sloppy, and not very maintainable.
This is what I'm trying to achieve:
let timerId;
const startTheTimer = () => {
timerId = setTimeout(() => {
somestuff();
timerId = undefined;
}, 10000);
}
// Called whenever any mouse click or keyboard event happens
const userDidSomething = () => {
if (timerId) {
clearTimeout(timerId);
timerId = undefined;
}
}
So, my question is, how do I get the function userDidSomething() to be called?
Thanks.
Upvotes: 3
Views: 2348
Reputation: 164731
Your question doesn't seem to have much to do with Vue. You'd just need to attach an event listener to document
. For example
document.addEventListener('click', userDidSomething)
document.addEventListener('keydown', userDidSomething)
Note: Any event that is caught and has stopPropagation()
called will not reach the document
.
If your timer is set within a component, you should probably do all this in your component's mounted
lifecycle hook.
It would also be a good idea to clear the timeouts and remove the listeners in the beforeDestroy
hook.
For example
export default {
data () {
return {
timerId: null
}
},
methods: {
startTimer () {
this.timerId = setTimeout(...)
},
clearTimer () {
clearTimeout(this.timerId)
}
},
mounted () {
this.startTimer() // assuming you want to start the timer on mount
document.addEventListener('click', this.clearTimer)
document.addEventListener('keydown', this.clearTimer)
},
beforeDestroy () {
this.clearTimer()
document.removeEventListener('click', this.clearTimer)
document.removeEventListener('keydown', this.clearTimer)
}
}
Upvotes: 4