首页 > 解决方案 > 如果 X 秒内没有活动,则运行切换类名的函数。如果活动,停止切换功能并重置不活动计时器

问题描述

在 100 秒不活动后,我想运行一个每 10 秒切换一次类名“显示”的函数。(“显示”类名使模态出现)。

如果/当有用户活动时,我想删除“显示”类名(如果它当前已打开)并停止 10 秒切换循环功能。我希望只有在 100 秒不活动后才能再次运行此切换循环。

我似乎无法让切换循环功能在用户活动时停止。切换循环继续运行。任何帮助,将不胜感激!这是我所拥有的:

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();

标签: javascripttogglesetintervalclearinterval

解决方案


您可能会使用添加到的 CSS 动画.show而不是处理setInterval.
此外,您的代码可能更简单(请参见下面的代码段):

请注意,我减少了让您等待 100 秒的时间。

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>


推荐阅读