How to detect idle time in JavaScript elegantly?

前端 未结 30 2335
别跟我提以往
别跟我提以往 2020-11-21 11:51

Is it possible to detect \"idle\" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.

Idle time:

相关标签:
30条回答
  • 2020-11-21 12:56

    Debounce actually a great idea! Here version for jQuery free projects:

    const derivedLogout = createDerivedLogout(30);
    derivedLogout(); // it could happen that user 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 ) 
    }
    
    0 讨论(0)
  • 2020-11-21 12:57

    My answer was inspired by vijay's answer, but is a shorter, more general solution that I thought I'd share for anyone it might help.

    (function () { 
        var minutes = true; // change to false if you'd rather use seconds
        var interval = minutes ? 60000 : 1000; 
        var IDLE_TIMEOUT = 3; // 3 minutes in this example
        var idleCounter = 0;
    
        document.onmousemove = document.onkeypress = function () {
            idleCounter = 0;
        };
    
        window.setInterval(function () {
            if (++idleCounter >= IDLE_TIMEOUT) {
                window.location.reload(); // or whatever you want to do
            }
        }, interval);
    }());
    

    As it currently stands, this code will execute immediately and reload your current page after 3 minutes of no mouse movement or key presses.

    This utilizes plain vanilla JavaScript and an immediately-invoked function expression to handle idle timeouts in a clean and self-contained manner.

    0 讨论(0)
  • 2020-11-21 12:58

    All the previous answers have an always-active mousemove handler. If the handler is jQuery, the additional processing jQuery performs can add up. Especially if the user is using a gaming mouse, as many as 500 events per second can occur.

    This solution avoids handling every mousemove event. This result in a small timing error, but which you can adjust to your need.

    function setIdleTimeout(millis, onIdle, onUnidle) {
        var timeout = 0;
        startTimer();
    
        function startTimer() {
            timeout = setTimeout(onExpires, millis);
            document.addEventListener("mousemove", onActivity);
            document.addEventListener("keydown", onActivity);
        }
    
        function onExpires() {
            timeout = 0;
            onIdle();
        }
    
        function onActivity() {
            if (timeout) clearTimeout(timeout);
            else onUnidle();
            //since the mouse is moving, we turn off our event hooks for 1 second
            document.removeEventListener("mousemove", onActivity);
            document.removeEventListener("keydown", onActivity);
            setTimeout(startTimer, 1000);
        }
    }
    

    http://jsfiddle.net/jndxq51o/

    0 讨论(0)
  • 2020-11-21 12:58

    I wrote a simple jQuery plugin that will do what you are looking for.

    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]
    });
    

    The script will listen for mouse, keyboard, touch and other custom events inactivity (idle) and fire global "activity" and "inactivity" events.

    Hope this helps :)

    0 讨论(0)
  • 2020-11-21 12:58

    Just a few thoughts, an avenue or two to explore.

    Is it possible to have a function run every 10 seconds, and have that check a "counter" variable? If that's possible, you can have an on mouseover for the page, can you not? If so, use the mouseover event to reset the "counter" variable. If your function is called, and the counter is above the range that you pre-determine, then do your action.

    Again, just some thoughts... Hope it helps.

    0 讨论(0)
  • 2020-11-21 12:58

    As simple as it can get, detect when mouse moves only:

    var idle = false;
    
    document.querySelector('body').addEventListener('mousemove', function(e) {
        if(idle!=false)idle = false;
    });
    
    var idleI = setInterval(function()
    {   
        if(idle == 'inactive')
        {
            return;
        }
    
        if(idle == true)
        {
            idleFunction();
            idle = 'inactive';
            return;
        }
    
        idle = true;
    }, 30000);// half the expected time, idle will trigger after 60s in this case.
    
    function idleFuntion()
    {
       console.log('user is idle');
    }
    
    0 讨论(0)
提交回复
热议问题