jQuery中的会话超时

5

如何在纯jQuery中编写sessionTimeOut功能而不使用任何插件?我想使用自己的警告UI。为了确定任何UI活动,我可以编写代码,但不确定如何将其与超时功能结合起来。

$('*').on('click', function () {
    console.log('click', this);

});

$('*').on('change', function() {
    console.log('change', this);
});

你有特别的原因想要重新发明轮子吗?市面上有许多高质量的会话超时jQuery插件。 - jbabey
它对于动态添加到页面的元素不起作用。甚至不要提它会向DOM添加大量处理程序。 - zerkms
你可以看一下现有解决方案的源代码,然后重新编写它们以适应自己的需求,如果你喜欢重新发明轮子和其他东西的话。 - Thor Jacobsen
2个回答

7

您可以在所有现代浏览器上捕获mousemove事件:

(function () {
    var timeoutSession;
    document.addEventListener('mousemove', function (e) {
        clearTimeout(timeoutSession);
        timeoutSession = setTimeout(function () {
            alert('Make SESSION expire');
            //call a script here to server...
        }, 30000); //30s
    }, true);
})();

mousemove 会不会有点过度呢?不过是一个不错的解决方案! - musefan
@musefan 当然这是一种过度解决方案,但这是我能想到的唯一完全相关的解决方案。使用 click 可能会更好,因为无论如何我们都不关心传播是否已停止。 - A. Wolff
工作得非常好。谢谢。 - Himanshu Yadav

1

根据Roasted的回答,但是使用ajax调用作为计时器重置动作,而不是鼠标移动:

(function (delay) {

    function getTimeout() {
        return setTimeout(function () {
            console.log('Make SESSION expire');
            //call a script here to server...
        }, delay);
    };

    // start the session timer
    var timeoutSession = getTimeout();

    $(document).ajaxSend(function() {
        // this event fires any time an ajax call is sent
        console.log('timeout reset');
        clearTimeout(timeoutSession);
        timeoutSession = getTimeout();
    });
})(30000); // <--- notice that you put the timeout delay here

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接