是否有可能在JavaScript中检测“空闲”时间?

我的主要用例可能是预取或预加载内容。

我将空闲时间定义为用户不活动或没有任何CPU使用的时间段


当前回答

JavaScript没有办法告诉CPU的使用情况。这将打破运行在沙盒中的JavaScript。

除此之外,连接页面的onmouseover和onkeydown事件可能会工作。

你也可以在onload事件中使用setTimeout来调度延迟后调用的函数。

// Call aFunction after 1 second
window.setTimeout(aFunction, 1000);

其他回答

我终于把这个工作在我的网站。我发现equiman的回答最有帮助。这个答案的问题是JavaScript中的alert()函数会暂停脚本执行。如果您像我一样希望发送一个警报,然后如果没有收到响应,站点将自动注销,那么暂停执行是一个问题。

解决方案是用自定义除法替换alert(),如下所述。

下面是代码:(注意:您需要更改第58行以重定向到您的站点的适当URL)

var inactivityTracker = function () { // Create an alert division var alertDiv = document.createElement("div"); alertDiv.setAttribute("style","position: absolute;top: 30%;left: 42.5%;width: 200px;height: 37px;background-color: red;text-align: center; color:white"); alertDiv.innerHTML = "You will be logged out in 5 seconds!!"; // Initialise a variable to store an alert and logout timer var alertTimer; var logoutTimer; // Set the timer thresholds in seconds var alertThreshold = 3; var logoutThreshold = 5; // Start the timer window.onload = resetAlertTimer; // Ensure timer resets when activity logged registerActivityLoggers(resetAlertTimer); // ***** FUNCTIONS ***** // // Function to register activities for alerts function registerActivityLoggers(functionToCall) { document.onmousemove = functionToCall; document.onkeypress = functionToCall; } // Function to reset the alert timer function resetAlertTimer() { clearTimeout(alertTimer); alertTimer = setTimeout(sendAlert, alertThreshold * 1000); } // Function to start logout timer function startLogoutTimer() { clearTimeout(logoutTimer); logoutTimer = setTimeout(logout, logoutThreshold * 1000); } // Function to logout function sendAlert() { // Send a logout alert document.body.appendChild(alertDiv); // Start the logout timer startLogoutTimer(); // Reset everything if an activity is logged registerActivityLoggers(reset); } // Function to logout function logout(){ //location.href = 'index.php'; } // Function to remove alert and reset logout timer function reset(){ // Remove alert division alertDiv.parentNode.removeChild(alertDiv); // Clear the logout timer clearTimeout(logoutTimer); // Restart the alert timer document.onmousemove = resetAlertTimer; document.onkeypress = resetAlertTimer; } }; <html> <script type="text/javascript" src="js/inactivityAlert.js"></script> <head> <title>Testing an inactivity timer</title> </head> <body onload="inactivityTracker();" > Testing an inactivity timer </body> </html>

你也许可以使用上面列出的鼠标移动技巧来检测网页上的不活跃状态,但这并不能告诉你用户不在另一个窗口或选项卡的另一个页面上,或者用户在Word、Photoshop或WoW中,只是在这个时候没有在看你的页面。

一般来说,我只会预取,并依赖于客户端的多任务处理。如果你真的需要这个功能,你可以在Windows中使用ActiveX控件做一些事情,但它充其量是丑陋的。

JavaScript没有办法告诉CPU的使用情况。这将打破运行在沙盒中的JavaScript。

除此之外,连接页面的onmouseover和onkeydown事件可能会工作。

你也可以在onload事件中使用setTimeout来调度延迟后调用的函数。

// Call aFunction after 1 second
window.setTimeout(aFunction, 1000);

对于其他有同样问题的用户。这是我刚编的一个函数。

它不会在用户每次鼠标移动时运行,也不会在每次鼠标移动时清除计时器。

<script>
// Timeout in seconds
var timeout = 10; // 10 seconds

// You don't have to change anything below this line, except maybe
// the alert('Welcome back!') :-)
// ----------------------------------------------------------------
var pos = '', prevpos = '', timer = 0, interval = timeout / 5 * 1000;
timeout = timeout * 1000 - interval;

function mouseHasMoved(e){
    document.onmousemove = null;
    prevpos = pos;
    pos = e.pageX + '+' + e.pageY;
    if(timer > timeout){
        timer = 0;
        alert('Welcome back!');
    }
}

setInterval(function(){
    if(pos == prevpos){
        timer += interval;
    }else{
        timer = 0;
        prevpos = pos;
    }
    document.onmousemove = function(e){
        mouseHasMoved(e);
    }
}, interval);
</script>

我也遇到过同样的问题,但我找到了一个很好的解决方案。

我使用jquery。无所事事,我只需要做:

$(document).idle({
  onIdle: function(){
    alert('You did nothing for 5 seconds');
  },
  idle: 5000
})

参见JsFiddle演示。

(仅供参考:查看后端事件跟踪Leads browserload)