【发布时间】:2015-06-12 16:40:02
【问题描述】:
我需要使用 setTimeout 或 setInterval 做某事,但无法使其工作。
假设我有一个图像在窗口完成渲染时加载,用户在 20 秒内保持空闲和/或做事,当这 20 秒过去后用户做了一些事情(点击、移动或滚动)我想刷新图像,但如果时间是 20 秒并且用户处于空闲状态,我想继续计算时间,直到用户进行交互,然后再清除值并重新开始观看。
案例:
-
图像加载、用户移动、保持空闲、点击(所有这些都在 20 秒内),然后用户在 20 秒后进行交互,因此图像刷新、setTimeout 或 setInterval 清除并重新开始
图像加载、用户移动、保持空闲(所有这一切都在 20 秒内),然后用户在 20 秒后保持空闲,因此图像不会刷新并且 setTimeout 或 setInterval 继续计数而不是清除等待用户进行交互以重新开始
无论如何我都无法采用这种方法。
我有这样的东西不起作用:
var refresh = setTimeout(function(){
console.log('Inside waiting for user interaction');
//If user is idle while inside here keep waiting and counting
$(document).on('mousemove click', function(){
console.log('Inside because of user interaction');
//Refresh image and then clearTimeOut
clearTimeout(refresh);
//Start again waiting for 20 seconds to get inside
setTimeout(refresh);
});
}, 20000); //20 seconds before waiting for user interaction
非常感谢!
【问题讨论】:
-
换一种说法,你只想考虑20秒后的活动?
-
您要多次添加事件监听器
-
@RoyJ 完全正确,我把描述复杂化了抱歉哈哈。我正是想要那个!
标签: javascript jquery settimeout setinterval