Reputation: 411
I would like a modal to pop up if there has been no action on the page by the user for the last 3 seconds. Is there a way for addEventListener to run a function upon no action for 3 seconds?
Upvotes: 2
Views: 690
Reputation: 27609
Use setTimeout()
to open the modal after 3 seconds and use an event listener for key presses (or key up, etc) to reset the timeout.
let timeout = undefined;
function resetTimer() {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
// open modal, call resetTimer() when it is closed to restart the check...
/*
modal.onClose = resetTimer;
modal.open();
*/
console.log('open modal');
}, 3000);
}
window.onload = function() {
// every time a key is pressed reset the timer
document.addEventListener('keypress', resetTimer);
// start the timer
resetTimer();
};
Upvotes: 1