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

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

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


当前回答

尝试freddoo的解决方案,但它在1分钟超时时间内不起作用,所以我稍微改变了它,以记录用户最后一次点击页面的日期+时间,在我的timerIncrement函数中,我计算当前时间和最后一次点击时间之间的差异,如果该值恰好大于或等于超时值,那么我重定向:

var clickedDate = new Date();
var idleTime = 1; //

function timerIncrement() {

    var nowDate = new Date();
    var diffMs = (nowDate - clickedDate); //Milliseconds between now & the last time a user clicked somewhere on the page
    var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); //Convert ms to minutes

    if (diffMins >= idleTime) {
        //Redirect user to home page etc...
    }
}

$(document).ready(function () {

    var idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    $(this).click(function (e) {
        clickedDate = new Date();
    });

});

其他回答

您可以在文档主体上附加一个单击或鼠标移动事件,以重置计时器。

有一个函数,你在定时间隔调用,检查定时器是否超过指定的时间(如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>

你肯定想知道window.requestIdleCallback(),它在浏览器空闲期间对要调用的函数进行排队。

您可以在Quicklink repo中看到这个API的优雅用法。

const requestIdleCallback = window.requestIdleCallback ||
  function (cb) {
    const start = Date.now();
    return setTimeout(function () {
      cb({
        didTimeout: false,
        timeRemaining: function () {
          return Math.max(0, 50 - (Date.now() - start));
        },
      });
    }, 1);
  };

上面代码的意思是:如果浏览器支持requestIdleCallback(检查兼容性),就使用它。如果不支持,则使用setTimeout(()=>{}, 1)作为回退,它应该在事件循环结束时将被调用的函数排队。

然后你可以这样使用它:

requestIdleCallback(() => {...}, {
    timeout: 2000
  });

第二个参数是可选的,如果希望确保函数执行,则可能需要设置一个超时。

下面是一个在Angular中完成的AngularJS服务。

/* Tracks now long a user has been idle.  secondsIdle can be polled 
   at any time to know how long user has been idle. */
fuelServices.factory('idleChecker',['$interval', function($interval){
    var self = {
        secondsIdle: 0,
        init: function(){
            $(document).mousemove(function (e) {
                self.secondsIdle = 0;
            });
            $(document).keypress(function (e) {
                self.secondsIdle = 0;
            });
            $interval(function(){
                self.secondsIdle += 1;
            }, 1000)
        }
    }
    return self;
}]);

请记住,这个空闲检查器将为所有路由运行,因此应该在angular应用程序加载时在.run()中初始化它。然后你可以使用idleChecker。在每个路由内的secondside。

myApp.run(['idleChecker',function(idleChecker){
    idleChecker.init();
}]);