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

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

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


当前回答

Debounce其实是个好主意!下面是一个用于无jquery项目的版本:

const derivedLogout = createDerivedLogout(30);
derivedLogout(); // It could happen that the user is too idle)
window.addEventListener('click', derivedLogout, false);
window.addEventListener('mousemove', derivedLogout, false);
window.addEventListener('keyup', derivedLogout, false);

function createDerivedLogout (sessionTimeoutInMinutes) {
    return _.debounce( () => {
        window.location = this.logoutUrl;
    }, sessionTimeoutInMinutes * 60 * 1000 )
}

其他回答

我创建了一个小的库来做这个:

https://github.com/shawnmclean/Idle.js

描述:

微小的JavaScript库报告用户在浏览器中的活动 (离开,空闲,没有看网页,在不同的标签,等)。这是独立的 其他JavaScript库,如jQuery。

Visual Studio用户可以从NuGet通过:

Install-Package Idle.js

类似于Peter J的解决方案(使用jQuery自定义事件)…

// Use the jquery-idle-detect.js script below
$(window).on('idle:start', function() {
  // Start your prefetch, etc. here...
});

$(window).on('idle:stop', function() {
  // Stop your prefetch, etc. here...
});

文件jquery-idle-detect.js

(function($, $w) {
  // Expose configuration option
  // Idle is triggered when no events for 2 seconds
  $.idleTimeout = 2000;

  // Currently in idle state
  var idle = false;

  // Handle to idle timer for detection
  var idleTimer = null;

  // Start the idle timer and bind events on load (not DOM-ready)
  $w.on('load', function() {
    startIdleTimer();
    $w.on('focus resize mousemove keyup', startIdleTimer)
      .on('blur', idleStart) // Force idle when in a different tab/window
      ;
  ]);

  function startIdleTimer() {
    clearTimeout(idleTimer); // Clear prior timer

    if (idle) $w.trigger('idle:stop'); // If idle, send stop event
    idle = false; // Not idle

    var timeout = ~~$.idleTimeout; // Option to integer
    if (timeout <= 100)
      timeout = 100; // Minimum 100 ms
    if (timeout > 300000)
      timeout = 300000; // Maximum 5 minutes

    idleTimer = setTimeout(idleStart, timeout); // New timer
  }

  function idleStart() {
    if (!idle)
      $w.trigger('idle:start');
    idle = true;
  }

}(window.jQuery, window.jQuery(window)))

我终于把这个工作在我的网站。我发现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>

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

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

<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插件,将做什么你正在寻找。

https://github.com/afklondon/jquery.inactivity

$(document).inactivity( {
    interval: 1000, // the timeout until the inactivity event fire [default: 3000]
    mouse: true, // listen for mouse inactivity [default: true]
    keyboard: false, // listen for keyboard inactivity [default: true]
    touch: false, // listen for touch inactivity [default: true]
    customEvents: "customEventName", // listen for custom events [default: ""]
    triggerAll: true, // if set to false only the first "activity" event will be fired [default: false]
});

脚本将监听鼠标,键盘,触摸和其他自定义事件不活动(空闲),并触发全局“活动”和“不活动”事件。