javascript 如果使用javascript几秒钟没有用户活动,如何刷新页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10849432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to refresh page if there is no user activity for few seconds using javascript
提问by Scorpyon
Possible Duplicate:
How To Alter This Code So That It Only Redirects If There Is No Mouse Movement
可能的重复:
如何更改此代码使其仅在没有鼠标移动时重定向
I want to refresh a web page if there is no activity by the user using Javascript. User activity as in Key Press or mouse click.
如果用户使用 Javascript 没有活动,我想刷新网页。用户活动,如按键或鼠标点击。
回答by Fabrizio Calderan
Here a basic example
这是一个基本的例子
(function(seconds) {
var refresh,
intvrefresh = function() {
clearInterval(refresh);
refresh = setTimeout(function() {
location.href = location.href;
}, seconds * 1000);
};
$(document).on('keypress click', function() { intvrefresh() });
intvrefresh();
}(15)); // define here seconds
This will refresh the page every 15 seconds without a keypress or a click event (but if you have same events defined elsewhere making a stopPropagation()
this won't properly work because the event won't be able to reach the element)
这将在没有按键或点击事件的情况下每 15 秒刷新一次页面(但如果您在其他地方定义了相同的事件,stopPropagation()
这将无法正常工作,因为该事件将无法到达该元素)
回答by Alnitak
Create a timer (setTimeout
) that will refresh the page, and every time there's a key press or mouse press, just restart the timer.
创建一个setTimeout
将刷新页面的计时器 ( ),每次有按键或鼠标按下时,只需重新启动计时器。
See this questionfor code that does most of what you want.
请参阅此问题以了解执行您想要的大部分内容的代码。
FWIW, here's F.Calderan's answer rewritten to:
FWIW,这是 F.Calderan 的答案改写为:
- eliminate unnecessary closures
- separate the actionfrom the repetition, by suppling the action as a callback
- 消除不必要的关闭
- 分离作用从所述重复,通过suppling动作作为回调
--
——
function setIdle(cb, seconds) {
var timer;
? ? var interval = seconds * 1000;
function refresh() {
? ? ? ? ? ? clearInterval(timer);
? ? ? ? ? timer = setTimeout(cb, interval);
? ? };
? ? $(document).on('keypress click', refresh);
? ? refresh();
}
setIdle(function() {
location.href = location.href;
}, 15);