如何在用户空闲时触发事件

时间:2015-03-19 15:59:14

标签: javascript jquery

当用户在指定时间内从网站闲置时,如何触发JQuery事件,并在鼠标移动,滚动或按键时重置计时器。

2 个答案:

答案 0 :(得分:2)

这可以通过使用setTimeout函数在指定的秒数结束时触发。如果在此期间基本上发生任何事情(鼠标移动,滚动页面或按下某个键),则重置超时时间。

在第三行设置空闲时段。

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)

答案 1 :(得分:1)

这是一个使用JQuery处理mousemove和keypress事件的简单脚本。如果时间到期,则会触发spinner-wrap事件。

    <script type="text/javascript">
    var idle = 0;
    $(document).ready(function () {
        //Increment the idle time counter every seconds.
        var idleInterval = setInterval(timerIncrement, 1000); // 1 seconds
        //Zero the idle timer on mouse move.
        $(this).mousemove(function (e) {
            idle = 0;
        });
        // zero the idle timer on keypress
        $(this).keypress(function (e) {
            idle = 0;
        });
    });

    function timerIncrement() {
        idle = idle + 1;
        if (idle > 5) { // 5 seconds
        $('.spinner-wrap').trigger('click');
        }
    }
    </script>   
相关问题