After 100 seconds of inactivity, I want to run a function that toggles a classname "show" every 10 seconds. (The 'show' classname makes a modal appear).
If/when there is user activity, I want to remove the 'show' classname (if it's currently toggled on) and also stop the 10-second toggle cycling function. I want this toggle cycling to run again only after there's been inactivity for 100 seconds.
I can't seem to get the toggle cycling function to stop upon user activity. The toggle cycle just continues to run. Any help would be appreciated! Here's what I have:
var el = document.querySelector('#element');
var toggle = function() {
el.classList.toggle('show');
}
function toggleTimer() {
var u;
window.onload = resetTimer;
window.onmousemove = resetTimer;
window.onmousedown = resetTimer;
window.ontouchstart = resetTimer;
window.onclick = resetTimer;
window.onkeypress = resetTimer;
window.addEventListener('scroll', resetTimer, true);
function toggleCycle() {
setInterval(toggle, 10000);
}
function resetTimer() {
clearTimeout(u);
u = setTimeout(toggleCycle, 100000);
el.classList.remove('show');
clearInterval(toggleCycle);
}
}
toggleTimer();
You might use CSS animation added to .show
instead of handling setInterval
.
Also your code might be simpler (see the snippet below):
Please note that I reduced times not to have you waiting for 100 secs.
var el = document.querySelector('#element');
var timer = 5000, tick = 1000;
const resetTimer = () => (timer = 5000) && el.classList.remove('show');
['load', 'touchstart', 'mousedown', 'mousemove', 'keydown', 'scroll']
.forEach(e => document.addEventListener(e, resetTimer));
setInterval(() => (timer -= tick) || el.classList.add('show'), tick);
h1:not(.show) {display: none}
.show {animation: togg 2s linear infinite alternate}
@keyframes togg {
40% {opacity:1}
50% {opacity:0}
100% {opacity:0}
}
<h1 id="element">SHOW</h1>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments