How to detect idle time in JavaScript elegantly?

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

    Try this code, it works perfectly.

    var IDLE_TIMEOUT = 10; //seconds
    var _idleSecondsCounter = 0;
    
    document.onclick = function () {
        _idleSecondsCounter = 0;
    };
    
    document.onmousemove = function () {
        _idleSecondsCounter = 0;
    };
    
    document.onkeypress = function () {
        _idleSecondsCounter = 0;
    };
    
    window.setInterval(CheckIdleTime, 1000);
    
    function CheckIdleTime() {
        _idleSecondsCounter++;
        var oPanel = document.getElementById("SecondsUntilExpire");
        if (oPanel)
            oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
        if (_idleSecondsCounter >= IDLE_TIMEOUT) {
            alert("Time expired!");
            document.location.href = "SessionExpired.aspx";
        }
    }
    

提交回复
热议问题