如何仅当用户存在(通过鼠标移动)时才使用 jQuery 执行 setTimeout()
我有一个通过 AJAX 更新
的函数:function update() {
<!-- .ajax() -->
setTimeout(update(), 3000);}
}
我需要的是,当用户不在网站上时,不会执行此函数,因此如果没有移动鼠标(我们假设如果移动它是在网站中)它不会更新 .mousemove()
。顺便问一下,我们还可以做其他事情来了解有人在网站上活跃吗?
这怎么能做到呢?先感谢您!
编辑:可能我解释得不好。我需要知道仅在有活动时更新的方法。就像 Facebook 对其新闻推送、首页所做的那样。谢谢!
I have a function that updates a <div />
via AJAX:
function update() {
<!-- .ajax() -->
setTimeout(update(), 3000);}
}
What I need is that this is not executed when the user is not present on the website, so if there is no movement of the mouse (we will suppose that if move it is in the website) it will not update .mousemove()
. By the way, there is any other thing that we can do to know is someone is active on the website?
How can this be done? Thank you in advance!
Edit: probably I explained bad. I need to know the way to only update when there is activity. Like Facebook does with his news feed, the front page. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 mousemove 处理程序来跟踪用户上次移动的时间,然后仅当用户上次在 X 秒内移动鼠标时才会发生该过程。但是,当然,如果用户坐在那里阅读某些内容,或者他们是一个以键盘为导向的人,那么他们往往会错过他们在那里......所以你可能想看看
keydown 也是如此。
这是一个鼠标移动示例:
那么您的更新代码可以执行以下操作:
偏离主题,但是您的更新代码有错误。您有:
...它将立即调用
update
,然后尝试使用其返回值来安排在三秒内发生的事情。如果您希望对update
的调用安排在三秒内发生,请在其后面省略()
:You could use a
mousemove
handler to track when the user last moved, and then have the process only happen if they last moved the mouse within X seconds. But of course, if the user is sitting there reading something, or if they're a keyboard-oriented kind of person, that will tend to miss that they are there... So you'd probably want to look atkeydown
as well.Here's a mousemove example:
Then your update code could do this:
Off-topic, but you have an error in your update code. You have:
...which will call
update
immediately and then try to use its return value to schedule something to happen in three seconds. If you want the call toupdate
to be scheduled to happen in three seconds, leave off the()
after it:我想我可能会得到这样的结果。避免日期算术。只关心自上次 update() 以来是否有一些活动。
编辑:我发现代码中存在缺陷。下面的说法比较合适:
I think I might have ended up with something such as this. Avoids date arithmetic. Only cares whether there's been some activity since the last update().
edit: I've discovered a flaw in the code. The following is more appropriate:
我认为没有简单的方法来确定用户是否存在,
我会使用
mousemove
、scroll
、keypress
的组合。I think there is no easy way to determine if the user is present
I would use a combination of
mousemove
,scroll
,keypress
.