How to detect idle time in JavaScript elegantly?

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

    Improving on Equiman's (original) answer:

    function idleLogout() {
        var t;
        window.onload = resetTimer;
        window.onmousemove = resetTimer;
        window.onmousedown = resetTimer;  // catches touchscreen presses as well      
        window.ontouchstart = resetTimer; // catches touchscreen swipes as well 
        window.onclick = resetTimer;      // catches touchpad clicks as well
        window.onkeydown = resetTimer;   
        window.addEventListener('scroll', resetTimer, true); // improved; see comments
    
        function yourFunction() {
            // your function for too long inactivity goes here
            // e.g. window.location.href = 'logout.php';
        }
    
        function resetTimer() {
            clearTimeout(t);
            t = setTimeout(yourFunction, 10000);  // time is in milliseconds
        }
    }
    idleLogout();
    

    .
    Apart from the improvements regarding activity detection, and the change from document to window, this script actually calls the function, rather than letting it sit idle by.

    It doesn't catch zero CPU usage directly, but that is impossible, because executing a function causes CPU usage. And user inactivity eventually leads to zero CPU usage, so indirectly it does catch zero CPU usage.

提交回复
热议问题