javascript - 如果 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();
解决方案
您可能会使用添加到的 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>
推荐阅读
- sql - 必须声明标量变量“@studentID”
- python - 你能用python制作一个不可编辑的pdf可编辑和可填充的吗?
- azure-devops - 如何将多个作业中的工件发布和下载到管道上的一个位置?
- javascript - 如何让 npm start 永远运行
- r - 绘制小标题的行
- product - 两队之间的季后赛最多包括五场比赛,第一队获胜三场,季后赛有多少种不同的方式?
- jenkins - Jenkins docker build customWorkspace 不起作用
- javascript - 从 Express JS 中的可选过滤器构建 MySQL 查询
- c# - 如何从对象列表中填充组合框
- javascript - 如何通过模板文字使所有按钮起作用