How to detect idle time in JavaScript elegantly?

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

    Here is the best solution I have found: http://css-tricks.com/snippets/jquery/fire-event-when-user-is-idle/

    Here is the JS:

    idleTimer = null;
    idleState = false;
    idleWait = 2000;
    
    (function ($) {
    
        $(document).ready(function () {
    
            $('*').bind('mousemove keydown scroll', function () {
    
                clearTimeout(idleTimer);
    
                if (idleState == true) { 
    
                    // Reactivated event
                    $("body").append("

    Welcome Back.

    "); } idleState = false; idleTimer = setTimeout(function () { // Idle Event $("body").append("

    You've been idle for " + idleWait/1000 + " seconds.

    "); idleState = true; }, idleWait); }); $("body").trigger("mousemove"); }); }) (jQuery)

提交回复
热议问题