How to detect idle time in JavaScript elegantly?

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

    Without using jQuery, only vanilla JavaScript:

    var inactivityTime = function () {
        var time;
        window.onload = resetTimer;
        // DOM Events
        document.onmousemove = resetTimer;
        document.onkeypress = resetTimer;
    
        function logout() {
            alert("You are now logged out.")
            //location.href = 'logout.html'
        }
    
        function resetTimer() {
            clearTimeout(time);
            time = setTimeout(logout, 3000)
            // 1000 milliseconds = 1 second
        }
    };
    

    And init the function where you need it (for example: onPageLoad).

    window.onload = function() {
      inactivityTime(); 
    }
    

    You can add more DOM events if you need to. Most used are:

    document.onload = resetTimer;
    document.onmousemove = resetTimer;
    document.onmousedown = resetTimer; // touchscreen presses
    document.ontouchstart = resetTimer;
    document.onclick = resetTimer;     // touchpad clicks
    document.onkeydown = resetTimer;   // onkeypress is deprectaed
    document.addEventListener('scroll', resetTimer, true); // improved; see comments
    

    Or register desired events using an array

    window.addEventListener('load', resetTimer, true);
    var events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
    events.forEach(function(name) {
     document.addEventListener(name, resetTimer, true); 
    });
    

    DOM Events list: http://www.w3schools.com/jsref/dom_obj_event.asp

    Remember use window, or document according your needs. Here you can see the differences between them: What is the difference between window, screen, and document in Javascript?

    Code Updated with @frank-conijn and @daxchen improve: window.onscroll will not fire if scrolling is inside a scrollable element, because scroll events don't bubble. window.addEventListener('scroll', resetTimer, true), the third argument tells the listener to catch event during capture phase instead of bubble phase.

提交回复
热议问题