How to detect idle time in JavaScript elegantly?

前端 未结 30 2383
别跟我提以往
别跟我提以往 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题