当用户处于空闲状态时,如何激发事件

How can i fire an event when the user is Idle

本文关键字:何激发 事件 状态 用户 于空闲      更新时间:2023-09-26

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

这是通过使用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)

这里有一个使用JQuery处理鼠标移动和按键事件的简单脚本。如果时间过期,将触发微调器换行事件。

    <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>