How to detect idle time in JavaScript elegantly?

前端 未结 30 2375
别跟我提以往
别跟我提以往 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: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/

提交回复
热议问题