用户空闲时触发事件

Avatar of Chris Coyier
Chris Coyier

请查看下面的两行注释代码,您可以在其中插入用户空闲时和用户返回时要执行的代码。在第三行设置空闲时间段,1000 表示 1 秒。

idleTimer = null;
idleState = false;
idleWait = 2000;

(function ($) {

    $(document).ready(function () {
    
        $('*').bind('mousemove keydown scroll', function () {
        
            clearTimeout(idleTimer);
                    
            if (idleState == true) { 
                
                // Reactivated event
                $("body").append("<p>Welcome Back.</p>");            
            }
            
            idleState = false;
            
            idleTimer = setTimeout(function () { 
                
                // Idle Event
                $("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");

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

此方法使用 setTimeout 函数在指定秒数结束时触发。如果在此期间发生任何事情(鼠标移动、页面滚动或按下键盘),超时时间段将重置。