我只想在人们不空闲时更新 useronline 数据库上的时间戳(键盘鼠标活动一段时间 - 我为此使用 jquery 插件)对我来说问题是我无法清除函数的间隔所以在我下面的测试脚本中,当它开始计数时它永远不会停止,即使再次激活它也会启动另一个计数器,这样它的计数速度就会提高一倍。我应该如何停止那个计时器?它就像计数器在空闲时从未启动过一样 - 所以它找不到它来停止它。
在真正的脚本中,计数器将是 $.get()-ing 更新 mysql 表的 php。出于这个原因,我正在使用间隔,或者它会在每次鼠标移动时都正确?那将加载服务器。
http://jsbin.com/uleza5进行测试,6秒内不要移动鼠标,然后看到空闲文本,然后移动鼠标,它会开始计数;6 秒后,它会在不活动时再次空闲。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script><script src="js/jquery_plugin_timer2.js"></script>
<script src="https://github.com/paulirish/jquery-idletimer/raw/master/jquery.idle-timer.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>timertest</title>
<script language="javascript">
$(document).ready(function(){
$('.status').html('active');
});
x = 0;
function count() {
x+=1;
$('.usercount').html(x);
}
(function() {
var timeout = 6000;
var it;
$(document).bind("idle.idleTimer", function() {
clearInterval(it);
$('.status').html('idle');
});
$(document).bind("active.idleTimer", function() {
var it = setInterval(count, 1000);
$('.status').html('active');
});
$.idleTimer(timeout);
})(jQuery);
</script>
</head>
<body>
<div class="status" style="border:1px dashed black; width:500px; height:50px;"></div>
<div class="usercount"style="border:1px dashed black; width:500px; height:50px;"></div>
</body>
</html>